我使用npm-request和npm-异步调用两个服务,结合它们的结果,并将它们显示给用户。(服务1:你好;服务2:世界;服务3:你好世界)。我想通过标头传递一个ID来跟踪呼叫的路由。
helloString = 'Nothing';
worldString = 'Yet';
async.series([
function(callback){
// call helloService
request('http://localhost:3000/hello', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
callback(null, body);
}
else {
callback(err, null);
}
})
},
function(callback){
// call worldService
request('http://localhost:3001/world', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
callback(null, body);
}
else {
callback(err, null);
}
})
}
],
// optional callback
function(err, results){
// results is now equal to ['hello', 'world']
console.log('*************');
console.log(results[0] + ' ' + results[1]);
console.log('*************');
res.send(results[0] + ' ' + results[1]);
});我想要做的是拦截这两个调用并添加一个自定义标头,就像我这样写的:
request({url: 'http://localhost:3000/hello', headers: {'id': '12345'}}, function (error, response, body) {...但不必每次都手动输入。
到目前为止,我已经尝试将其放入每个服务的server.js文件中:
app.use(function(req,res,next){
if (req.headers["id"]) {
console.log('service was given id: ' + req.headers["id"]);
res.writeHead(200, {"id": req.headers["id"]});
console.log('set res header id to ' + res._headers["id"]);
}
else {
console.log("I wasn't passed the ID");
}
next();
});我似乎正确地获取了ID,但在将其传递到下一个服务时遇到了困难。这是我正在犯的错误:
_http_outgoing.js:335
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.提前谢谢你!
发布于 2015-09-10 18:17:39
按照jFriend00的建议,我在请求()模块周围构建了一个包装器,以实现我想做的事情!这是一次很好的学习体验,如果你想看看我是怎么做到的,我把它写成了这里。
发布于 2015-09-04 16:04:44
在您的server.js服务文件中,更改以下内容:
res.writeHead(200, {"id": req.headers["id"]});对此:
res.setHeader("id", req.headers["id"]);res.writeHead()正在尝试写出所有的标头并完成响应的头部分。这还不是您想要在中间件中做的事情。
https://stackoverflow.com/questions/32402027
复制相似问题