您可以通过重载响应对象的writeHead函数来实现。例如,此代码会将“ foo”响应标头设置为值“ bar”。我已经指出了可以在其中添加自己的逻辑以更改标头值的地方。
JavaScript不是我的主要语言,因此可能有一种惯用的方法来重载writeHead方法。
httpProxy = require('http-proxy');
httpProxy.createServer(function (req, res, proxy) {
res.oldWriteHead = res.writeHead;
res.writeHead = function(statusCode, headers) {
/* add logic to change headers here */
var contentType = res.getHeader('content-type');
res.setHeader('content-type', 'text/plain');
// old way: might not work Now
// as headers param is not always provided
// https://github.com/nodejitsu/node-http-proxy/pull/260/files
// headers['foo'] = 'bar';
res.oldWriteHead(statusCode, headers);
}
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 3000
});
}).listen(8000);