ExpressJS抛出多个报头错误,而我似乎只发送一个报头



我有以下代码块:

router.put("/:_id", async (req: Request, res: Response) => {
try {
// Create the updated artist variable
const artist: IArtist = req.body;
const updatedArtist = await Artist.findOneAndUpdate({_id: req.params._id}, artist);
return res.sendStatus(200).json(updatedArtist);
} catch (err) {
// console.log(err);
return res.sendStatus(400).send("Couldn't update artist");
}

});

这会抛出以下错误:

(node:32408) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:561:11)
at ServerResponse.header (C:UsersthimoDocumentsGitHubFlexTixservernode_modulesexpresslibresponse.js:771:10)  
at ServerResponse.contentType (C:UsersthimoDocumentsGitHubFlexTixservernode_modulesexpresslibresponse.js:599:15)
at ServerResponse.sendStatus (C:UsersthimoDocumentsGitHubFlexTixservernode_modulesexpresslibresponse.js:357:8)
at C:UsersthimoDocumentsGitHubFlexTixserversrcroutesartists.ts:44:20
at step (C:UsersthimoDocumentsGitHubFlexTixserversrcroutesartists.ts:33:23)
at Object.next (C:UsersthimoDocumentsGitHubFlexTixserversrcroutesartists.ts:14:53)
at fulfilled (C:UsersthimoDocumentsGitHubFlexTixserversrcroutesartists.ts:5:58)
at processTicksAndRejections (internal/process/task_queues.js:95:5)

据我所知,我只发送了一个报头。我该如何解决这个问题?

您需要使用.status()而不是.sendStatus()。当你在.sendStatus()上使用.json().send()时,express试图在已经发送的响应上设置额外的标头,因为.sendStatus()

最新更新