【发布时间】:2018-05-29 05:58:27
【问题描述】:
我正在为我和我的朋友开发一款梦幻足球应用程序,但我遇到了这个古老的错误,而且这里回答的任何其他问题似乎都不适合我的情况。在下面的第一个代码块中,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)
【问题讨论】:
-
您的问题包含很多不相关的信息。尽量提供一个最小的、完整的和可验证的例子。 stackoverflow.com/help/mcve
-
@JemiSalo:已编辑
-
为什么要返回
if (error)中的函数?对我来说没有意义。您可以只throw error或将其传递给下一个中间件next(error)