nodejs 网络编程

网络编程

HTTP

websocket

埋点应用

// 埋点
const img = new Image();
img.src = '/api/users?abc=123123';

跨域

不同源浏览器就会报跨域问题

后端如何设置允许跨域 CORS

var server = http.createServer((req, res) => {
    const { method, url } = req;
    if (method === 'GET' && url === '/') {
        fs.readFile(__dirname + '/index.html', (err, data) => {
            res.setHeader('content-type', 'text/html;charset=utf8');
            res.end(data);
        });
    } else if (method === 'GET' && url === '/api/users') {
        const txt = { 'a': 'a', 'b': 'b' };
        const txtStr = JSON.stringify(txt);
        res.writeHead(200, {
            'content-type': 'application/json',
            'Access-Control-Allow-Origin': 'http://localhost:8090'
        }).end(txtStr);
    } else if (method === 'OPTIONS' && url === '/api/users') {
        // 出现预检处理
        const txt = { 'c': 'c', 'd': 'd' };
        const txtStr = JSON.stringify(txt);
        res.writeHead(200, {
            'Access-Control-Allow-Origin': 'http://localhost:8090',
            'Access-Control-Allow-Headers': 'X-xxx,Content-Type',
            'Access-Control-Allow-Methods': 'PUT',
        }).end(txtStr);
    } else {
        res.setHeader('content-type', 'text/html;charset=utf8');
        res.end('错误啦!!!');
    }
});

正向代理和反向代理

proxy代理

const Express = require('express');
const proxy = require('http-proxy-middleware');
const app = Express();

app.use(Express.static(__dirname + '/'));

// headers 里有一个changeOrigin
app.use('/api', proxy({ target: 'http://localhost:4000', changeOrigin: false }));
app.use('/aa', proxy({ target: 'http://localhost:4000', changeOrigin: false }));
// 加上反向代理
app.listen(8090);

module.exports = app;

posted on 2020-01-03 21:14  2481  阅读(197)  评论(0编辑  收藏  举报

导航