Bla*_*kus 2 connect node.js node-http-proxy
在Node上使用连接库,我尝试在使用node-http-proxy代理它之前检索请求体.
从Node v4开始,我们必须使用bodyParser之类的中间件(或者只是请求数据/结束事件)来检索POST请求体.
问题是,它似乎消耗了请求流,并且在被代理时请求超时.
这是代码,首先我用数据事件检索正文,然后我将它提供给http-proxy,但请求超时.
var httpProxy = require('http-proxy');
var connect = require('connect');
var proxy = new httpProxy.createProxyServer({
target: {
host: 'localhost',
port: 9015
}
});
var app = connect()
.use(function (req, res, next) {
var bodyBuffer = '';
req.on('data', function (data) {
bodyBuffer += data;
});
req.on('end', function () {
req.body = buffer;
next();
});
})
.use(function (req, res) {
//I can use req.body now
//But the proxy request timeouts
proxy.web(req, res);
});
http.createServer(app).listen(3000);
Run Code Online (Sandbox Code Playgroud)
当读取流以检索请求主体时,在代理请求时不能再次发送它.
为此,http-proxy web()方法有一个选项来发送已经缓冲的请求.
在第一个中间件上,PassThrough使用包含您检索的主体的缓冲区构造流.例如,将它存储在请求中(可能有更好的方法来存储它),供以后使用.
var stream = require('stream');
req.on('end', function() {
req.body = buffer;
var bufferStream = new stream.PassThrough();
bufferStream.end(new Buffer(buffer));
req.bodyStream = bufferStream;
next();
});
Run Code Online (Sandbox Code Playgroud)
然后proxy.web()在buffer属性上的第三个调用参数上添加它.
proxy.web(req, res, {buffer: req.bodyStream});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
849 次 |
| 最近记录: |