• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

启动一个node后台服务

互联网 diligentman 7天前 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的请求 -->
    <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>
        // axios的请求
        (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('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

<!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 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;

喜欢 (0)
==========================