Mat*_*can 10 javascript node.js express node-http-proxy body-parser
我也把这个发布到了相关的问题上http-proxy.
我正在使用http-proxy,express所以我可以拦截我的客户端和api之间的请求,以便添加一些cookie进行身份验证.
为了进行身份验证,客户端必须发送一个POST请求x-www-form-urlencoded作为content-type.所以我使用body-parser中间件来解析请求体,以便我可以在请求中插入数据.
http-proxy与使用问题,body-parser恐怕是因为它分析的身体流,永远不会关闭它,因此代理从来就不曾完成请求.
http-proxy示例中有一个解决方案,在解析了我尝试使用的请求之后"重新流式传输".我也尝试connect-restreamer在同一个问题上使用该解决方案,但没有运气.
我的代码看起来像这样
var express = require('express'),
bodyParser = require('body-parser'),
httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({changeOrigin: true});
var restreamer = function (){
return function (req, res, next) { //restreame
req.removeAllListeners('data')
req.removeAllListeners('end')
next()
process.nextTick(function () {
if(req.body) {
req.emit('data', req.body) //error gets thrown here
}
req.emit('end')
})
}
}
var app = express();
app.use(bodyParser.urlencoded({extended: false, type: 'application/x-www-form-urlencoded'}));
app.use(restreamer());
app.all("/api/*", function(req, res) {
//modifying req.body here
//
proxy.web(req, res, { target: 'http://urlToServer'});
});
app.listen(8080);
Run Code Online (Sandbox Code Playgroud)
我收到这个错误
/Code/project/node_modules/http-proxy/lib/http-proxy/index.js:119
throw err;
^
Error: write after end
at ClientRequest.OutgoingMessage.write (_http_outgoing.js:413:15)
at IncomingMessage.ondata (_stream_readable.js:540:20)
at IncomingMessage.emit (events.js:107:17)
at /Code/project/lib/server.js:46:25
at process._tickCallback (node.js:355:11)
Run Code Online (Sandbox Code Playgroud)
我试图调试流量,但抓住了吸管.有什么建议吗?
Vic*_*nez -4
http-proxy 在处理 POST 主体方面是出了名的糟糕,尤其是在最新版本的 Node 中;中间件黑客并不总是适用于所有 POST 请求。我建议您使用专用的 http 代理引擎,例如 NGINX 或 HAPROXY 中的引擎,它们效果最好。