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('错误啦!!!');
    }
});

正向代理和反向代理

猜你喜欢

转载自www.cnblogs.com/daixixi/p/12146988.html