我正在处理nodejs代理服务器修改(写入)响应。
我想通过节点代理服务器实现一个站点的自动登录,为此我必须在数据库中进行查询,然后可以修改响应,但似乎要求在req.write
之前获得Error: write after end
之前结束>
以下是我到目前为止的实现。
var express = require('express');
var proxy = require('http-proxy-middleware');
var options = {
target: 'http://example.com/', // target host
changeOrigin: true,
onProxyReq: function onProxyReq(proxyReq, req, res) {
var _write = res.write;
var body = "";
proxyReq.on('data', function(data) {
data = data.toString('utf-8');
body += data;
});
res.write = function (data) {
try{
//I have database query here instead of setTimeout
setTimeout(function(){
/* Modified response here and write */
_write.call(res, data); //can't write because req already end
},3000);
} catch (err) {
console.log('err',err);
}
}
}
}
// create the proxy (without context)
var exampleProxy = proxy(options);
// mount `exampleProxy` in web server
var app = express();
app.use('/', exampleProxy);
app.listen(8080);
有人可以指导我如何实现这一目标吗?