发送到客户端后无法设置标头 - Node / Mongoose / Express

时间:2018-05-28 18:15:45

标签: node.js express mongoose

我正在为我和我的朋友制作一个幻想足球应用程序,但我收到了这个古老的错误,似乎这里回答的其他问题都不适合我的情况。在下面的第一个代码块中,console.log正在返回正确的数据,因此我非常确定res.json(populatedClub)应该正常工作。我在代码中的其他任何地方都找不到触发此事件链中的另一个res.send()res.json()的内容。

还有其他人能够看到我不是吗?

我的路线:

fantasyClubRouter.get('/:userId', 
  (req, res) => {
    FantasyClub
    .findOne({manager: req.params.userId})
    .populate({
      path: 'manager',
      model: 'User'
    })
    .exec((error, populatedClub) => {
      if (error) {
        return () => {throw new Error(error)};
      }
      console.log('populatedClub:', populatedClub);
      res.json(populatedClub);
    })
    .catch(error => {
      throw new Error(error);
    });
  }
);

错误堆栈:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
     at ServerResponse.setHeader (_http_outgoing.js:471:11)
     at ServerResponse.header (/home/ubuntu/workspace/node_modules/express/lib/response.js:767:10)
     at ServerResponse.send (/home/ubuntu/workspace/node_modules/express/lib/response.js:170:12)
     at ServerResponse.json (/home/ubuntu/workspace/node_modules/express/lib/response.js:267:15)
     at FantasyClub.findOne.populate.exec (/home/ubuntu/workspace/server/fantasyClub-routes.js:18:11)
     at /home/ubuntu/workspace/node_modules/mongoose/lib/model.js:4187:16
     at (anonymous function).call (/home/ubuntu/workspace/node_modules/mongoose/lib/query.js:3128:7)
     at process.nextTick (/home/ubuntu/workspace/node_modules/mongoose/lib/query.js:2019:28)
     at process._tickCallback (internal/process/next_tick.js:61:11)
 Emitted 'error' event at:
     at /home/ubuntu/workspace/node_modules/mongoose/lib/model.js:4189:13
     at (anonymous function).call (/home/ubuntu/workspace/node_modules/mongoose/lib/query.js:3128:7)
     at process.nextTick (/home/ubuntu/workspace/node_modules/mongoose/lib/query.js:2019:28)
     at process._tickCallback (internal/process/next_tick.js:61:11)

1 个答案:

答案 0 :(得分:0)

我弄清楚我做错了什么,而且这很简单,我几乎不好意思承认它,但它就在这里。

我从较旧版本的Mongoose更新,忘了更新我的代码。始终确保您的代码符合文档对您正在使用的库版本的说法。

这是工作代码:

fantasyClubRouter.get('/:userId', (req, res) => { FantasyClub .findOne({manager: req.params.userId}) .populate({ path: 'manager', model: 'User' }) .then(populatedClub => { res.json(populatedClub); }) .catch(error => { throw new Error(error); }); } );