【问题标题】:Cannot set headers after they are sent to the client with postman使用邮递员将标头发送到客户端后无法设置标头
【发布时间】:2021-08-26 05:35:57
【问题描述】:

我的 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.

有人有解决方案吗? 在此先感谢:)

【问题讨论】:

  • 将错误消息和代码作为文本而不是图像发布。
  • 感谢您的建议 :)

标签: javascript node.js api rest


【解决方案1】:

.then(res.status(201).json({ message : "registered object !" })) 行立即调用res.status(201).json({ message : "registered object !" }),并使用该调用的结果作为传递给then 的参数。

因此,无论save 是否成功,您的res.status(201).json({ message : "registered object !" }) 都将始终被执行,并且会在保存发生之前被调用。

根据错误消息,您的保存失败,因此您首先调用res.status(201).json({ message : "registered object !" }),它将标头和正文发送到客户端,然后您调用res.status(400).json({ error }),它尝试再次发送标头,但请求已经发送。

您必须使用例如将then 中的部分转换为回调一个箭头函数:.then(() => res.status(201).json({ message : "registered object !" }))

【讨论】:

  • 感谢您的解决方案和解释!你的建议有效! :)
猜你喜欢
  • 2021-06-18
  • 1970-01-01
  • 2022-01-14
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多