首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过链式服务传递标头

通过链式服务传递标头
EN

Stack Overflow用户
提问于 2015-09-04 15:50:08
回答 2查看 53关注 0票数 0

我使用npm-request和npm-异步调用两个服务,结合它们的结果,并将它们显示给用户。(服务1:你好;服务2:世界;服务3:你好世界)。我想通过标头传递一个ID来跟踪呼叫的路由。

代码语言:javascript
复制
  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]);
  });

我想要做的是拦截这两个调用并添加一个自定义标头,就像我这样写的:

代码语言:javascript
复制
request({url: 'http://localhost:3000/hello', headers: {'id': '12345'}}, function (error, response, body) {...

但不必每次都手动输入。

到目前为止,我已经尝试将其放入每个服务的server.js文件中:

代码语言:javascript
复制
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,但在将其传递到下一个服务时遇到了困难。这是我正在犯的错误:

代码语言:javascript
复制
_http_outgoing.js:335
    throw new Error('Can\'t set headers after they are sent.');
          ^
Error: Can't set headers after they are sent.

提前谢谢你!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-09-10 18:17:39

按照jFriend00的建议,我在请求()模块周围构建了一个包装器,以实现我想做的事情!这是一次很好的学习体验,如果你想看看我是怎么做到的,我把它写成了这里

票数 0
EN

Stack Overflow用户

发布于 2015-09-04 16:04:44

在您的server.js服务文件中,更改以下内容:

代码语言:javascript
复制
res.writeHead(200, {"id": req.headers["id"]});

对此:

代码语言:javascript
复制
res.setHeader("id", req.headers["id"]);

res.writeHead()正在尝试写出所有的标头并完成响应的头部分。这还不是您想要在中间件中做的事情。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32402027

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档