问题描述
我的 POST 有问题。我正在尝试使用 Postman Postman screen 发送请求,但在终端中出现错误。 我的代码:
exports.createSauce = (req,res,next) => {
const sauce = new Sauce({
...req.body
})
sauce.save()
.then(res.status(201).json({ message : "registered object !" }))
.catch(error => res.status(400).json({ error }))
}
我的错误信息:
(node:2808) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:481:11)
at ServerResponse.header (C:\Users\Admin\Desktop\Workspace\P6_saumureau_thibaud\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (C:\Users\Admin\Desktop\Workspace\P6_saumureau_thibaud\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (C:\Users\Admin\Desktop\Workspace\P6_saumureau_thibaud\node_modules\express\lib\response.js:267:15)
at sauce.save.then.catch.error (C:\Users\Admin\Desktop\Workspace\P6_saumureau_thibaud\controllers\sauce.js:9:37)
at process._tickCallback (internal/process/next_tick.js:178:7)
(node:2808) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block,or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:2808) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future,promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
有人有解决方案吗? 提前致谢:)
解决方法
行 .then(res.status(201).json({ message : "registered object !" }))
立即调用 res.status(201).json({ message : "registered object !" })
并将该调用的结果用作传递给 then
的参数。
因此,无论 res.status(201).json({ message : "registered object !" })
是否成功,您的 save
都将始终执行,并且会在保存发生之前被调用。
根据错误消息,您的保存失败,因此您首先调用 res.status(201).json({ message : "registered object !" })
将标头和正文发送到客户端,然后调用 res.status(400).json({ error })
尝试再次发送标头,但请求是已经发送。
您必须使用例如将 then
中的部分转换为回调箭头函数:.then(() => res.status(201).json({ message : "registered object !" }))