nodeバックグラウンドサービスの開始

4507 ワード

koaを使用して作成する方法
入口index.html



    
    
    Document


    
    
// axios (async () => { const res2 = await axios.post('/api/users', { key: 'value', }); document.writeln(`RES : ${JSON.stringify(res2.data)}`) })()

index.js
const Koa = require('koa');
const app = new Koa();
const router = require('koa-router')();

const bodyParser = require('koa-bodyparser');     //     form         
app.use(require('koa-static')(__dirname + '/'));  //   index.html  
app.use(bodyParser());

router.post('/add', async (ctx, next) => {
    console.log('body', ctx.request.body)
    ctx.body='  post  ';
})
router.get('/add', async (ctx, next) => {
    console.log('body', ctx.request.body)
})
router.post('/api/users', async (ctx, next) => {
    console.log('body', ctx.request.body)
})

app.use(router.routes())
app.listen(3000)

httpを使用して、ドメイン間リクエスト(順方向エージェント、逆方向エージェント)を含むリクエストを作成します.
index.html



    
    
    Document


    
    
        (async () => {
            //     ,         (            )
            axios.defaults.baseURL = 'http://localhost:4000';
            axios.defaults.withCredentials = true
            
            const res2 = await axios.post('/api/users', {
                key: 'value',
            });
            document.writeln(`RES : ${JSON.stringify(res2.data)}`)
        })()
    



index.js
const api = require('./api');
const proxy = require('./proxy');
api.listen(4000);
proxy.listen(3000);

proxy.js
const express = require('express');
const app = express();
app.use(express.static(__dirname + '/'));

//     ,         (            )
const {createProxyMiddleware} = require('http-proxy-middleware');  //     
app.use('/api', createProxyMiddleware({
    target: 'http://localhost:4000',
    changeOrigin: false,
}))

module.exports = app;

api.js
const http = require('http');
const fs = require('fs');
const app = http.createServer((req, res) => {
    const {url, method, headers} = req;

    //   index.html
    if (url === '/' && method === 'GET') {
        fs.readFile('index.html', (err, data) => {
            if (err) {
                res.writeHead(500, {'Content-Type': 'text/plain'});
                res.end('     ')
            }
            res.writeHead(200, {'Content-Type': 'text/html'})
            res.end(data)
        })
        
    //   /api/users
    } else if ((method === 'GET' || method === 'POST') && url === '/api/users') {
        
        //          (            )
        res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000')
        res.setHeader('Access-Control-Allow-Credentials', 'true')
        res.setHeader('Content-Type', 'application/json');
        
        res.setHeader('Set-Cookie', 'cookie=val12123')
        res.end(JSON.stringify([{name: 'tom'}]))
    } else if (method === 'OPTIONS' && url === '/api/users') {
    
        //          (            )
        res.setHeader('Access-Control-Allow-Credentials', 'true')
        res.writeHead(200, {
            'Access-Control-Allow-Origin' : 'http://localhost:3000',
            'Access-Control-Allow-Headers' : 'X-Token,Content-Type',
            'Access-Control-Allow-Methods' : 'PUT',
        })
        
        res.end()
    }
})
module.exports = app;