http-proxy-middleware阻止网页

时间:2018-05-25 04:42:38

标签: node.js http express http-proxy

您是否知道为什么在浏览器上打开以下网页时会一直加载(阻止)?

http://localhost:3002/

如果在行return;之前放置res.writeHead = (...args) => { writeHeadArgs = args; };,页面工作正常但不执行代码逻辑。如果您在该行之后放置return,它会一直保持加载状态。

生成

$ node server.js

server.js

var express = require('express');
var http = require('http');
var proxy = require('http-proxy-middleware');

function bodyTransform(body) {
    return body.replace('World', 'People');
}

var onProxyRes = (proxyRes, req, res) => {

    const end = res.end;
    const writeHead = res.writeHead;
    let writeHeadArgs;
    let body;
    var buffer = new Buffer('');

    proxyRes.on('data', (chunk) => {
        console.log("inside: .on('data', ...)");
        buffer = Buffer.concat([buffer, chunk]);
    });
    proxyRes.on('end', () => {
        console.log("inside: .on('end', ...)");
        body = buffer.toString('utf8');
    });

    res.write = () => { };
    res.writeHead = (...args) => { writeHeadArgs = args; };

    res.end = () => {
        const output = bodyTransform(buffer.toString());
        res.setHeader('content-length', output.length);
        if (writeHeadArgs)
            writeHead.apply(res, writeHeadArgs);
        end.apply(res, [output]);
        console.log('after: end.apply(res, [output]);');
    };
}

const portApp01 = 3001;
const app01 = express()
app01.get('/', (req, res) => {
    res.send('Hello World!');
});
app01.listen(portApp01, () => {
    console.log('app01 is listening on port: ' + portApp01);
});

const portProxy = 3002;
const appProxy = express()
appProxy.use(proxy({ target:'http://localhost:3001', onProxyRes: onProxyRes, changeOrigin: true }));
http.createServer(appProxy).listen(portProxy, function () {
    console.log('appProxy is listening on port: ' + portProxy);
});

这是我在终端上获得的输出:

[HPM] Proxy created: /  ->  http://localhost:3001
app01 is listening on port: 3001
appProxy is listening on port: 3002
inside: .on('data', ...)
inside: .on('end', ...)
after: end.apply(res, [output]);

关于如何解决这个问题的任何想法?

谢谢!

0 个答案:

没有答案