启动一个node后台服务

码农天地 -
启动一个node后台服务
使用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;
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。
下一篇: 赛博朋克2077

Tags 标签

加个好友,技术交流

1628738909466805.jpg