关于node.js:启动一个node后台服务

50次阅读

共计 2863 个字符,预计需要花费 8 分钟才能阅读完成。

应用 koa 创立的形式

入口 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="/add" method="POST">
        <input type="text" name="key1">
        <input type="submit" value="Add">
    </form>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.js"></script>
    <script>
        (async () => {
            const res2 = await axios.post('/api/users', {key: 'value',});
            document.writeln(`RES : ${JSON.stringify(res2.data)}`)
        })()
    </script>
</body>
</html>

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('get');
    ctx.body='这是 get 申请';
})
router.post('/api/users', async (ctx, next) => {console.log('get');
    ctx.body='这是 get 申请, /api/users';
})

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

应用 http 的形式创立蕴含跨域的申请

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.js"></script>
    <script>
        (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)}`)
        })()
    </script>
</body>
</html>

index.js

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

proxy.js

const express = require('express');
const {createProxyMiddleware} = require('http-proxy-middleware');

const app = express();
app.use(express.static(__dirname + '/'));
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;

    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)
        })
    } 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('Set-Cookie', 'cookie=val12123')
        res.setHeader('Content-Type', 'application/json');
        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;

正文完
 0