node.js express req.pipe() 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18728039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
express req.pipe() does not work
提问by user606521
- I want to listen to incoming POST request in express.
- I want to pipe this request to another server
- I want to receive response inside express handler (I dont want to pipe response to express res stream)
- 我想在 express 中收听传入的 POST 请求。
- 我想将此请求通过管道传输到另一台服务器
- 我想在 express 处理程序中接收响应(我不想通过管道响应表达 res 流)
For now I have following code:
现在我有以下代码:
app.post('server1',function(req,res,next){
var request = require('request');
req.pipe(request.post('server2')).pipe(res);
}
So this does not work - request is not even piped to server2 - I checked it and there is no incoming request.
所以这不起作用 - 请求甚至没有通过管道传送到 server2 - 我检查过它并且没有传入的请求。
I solved points 1 & 2 like this:
我像这样解决了第 1 点和第 2 点:
var bodyParser = express.bodyParser();
app.use(function(req,res,next){
if(req.path == '/server1' && req.method == 'POST') {
return next();
}
else {
bodyParser(req,res,next);
}
});
Not very nice but it works - it just disables bodyparser for a single route (POST /server1).
不是很好,但它有效 - 它只是禁用单个路由(POST / server1)的 bodyparser。
But I still don't know how to obtain json response body from piped request - I have following code:
但我仍然不知道如何从管道请求中获取 json 响应体 - 我有以下代码:
app.post('/server1',function(req,res,next){
var request = require('request');
var pipe = req.pipe(request.post('/server2'));
pipe.on('end',function(){
var res2 = pipe.response;
console.log(res2);
});
});
res2object has correct statusCode and headers and so on but it does not contain body - how I can get this from the res2object? /server2returns some data in json but I dont know how to read it from response...
res2对象具有正确的状态代码和标题等,但它不包含正文 - 我如何从res2对象中获取它?/server2在 json 中返回一些数据,但我不知道如何从响应中读取它...
回答by IvanM
It doesn't work because bodyParser intercepts all the bodies with parsers
它不起作用,因为 bodyParser 用解析器拦截了所有主体
回答by robertklep
I think you're almost there. You should listen on dataevents on the pipe to collect the response:
我想你快到了。您应该监听data管道上的事件以收集响应:
app.post('/server1',function(req,res,next) {
var request = require('request');
var pipe = req.pipe(request.post('/server2'));
var response = [];
pipe.on('data',function(chunk) {
response.push(chunk);
});
pipe.on('end',function() {
var res2 = Buffer.concat(response);
console.log(res2);
// don't forget to end the 'res' response after this!
...
});
});
However, since you solved the "bodyParser() getting in the way" problem, you can also use your initial pipe setup if you just want to return the response generated by server2 (also, be sure to use proper URL's when using request).
但是,由于您解决了“bodyParser() 妨碍”问题,如果您只想返回 server2 生成的响应,您也可以使用初始管道设置(另外,在使用 时请务必使用正确的 URL request)。

