![](/img/trans.png)
[英]Node.js Express.js Mongoose Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
[英]Cannot set headers after they are sent to the client - Node/Mongoose/Express
我正在為我和我的朋友開發一個幻想足球應用程序,但是我遇到了這個已久的錯誤,看來這里回答的其他任何問題都不符合我的情況。 在下面的第一段代碼中, 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)
我弄清楚自己做錯了什么,它是如此簡單,以至於我幾乎不敢承認它,但是事情就這樣了。
我從較舊的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); }); } );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.