Node.js中ERR_HTTP_HEADERS_SENT错误:PostMan请求成功但控制台报错
问题描述
环境信息:
- Node.js 版本:v18.15.0
- Mongoose 版本:7.1.1
通过 PostMan 向/product接口发送数据时,数据能正常保存,但控制台抛出错误:Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
接口代码:
app.post('/product', async (req, res) => { try { const singleProduct = await product.create(req.body) res.sendStatus(200).json(singleProduct) } catch (error) { console.log(error.message); res.sendStatus(500).json({ message: error.message }) } })
错误栈:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at new NodeError (node:internal/errors:399:5) at ServerResponse.setHeader (node:_http_outgoing:663:11) at ServerResponse.header (F:\nodejsproject\crudapp\node_modules\express\lib\response.js:794:10) at ServerResponse.contentType (F:\nodejsproject\crudapp\node_modules\express\lib\response.js:624:15) at ServerResponse.sendStatus (F:\nodejsproject\crudapp\node_modules\express\lib\response.js:373:8) at F:\nodejsproject\crudapp\server.js:20:20 at process.processTicksAndRejections (node:internal/process/task_queues:95:5) { code: 'ERR_HTTP_HEADERS_SENT' }
问题原因及解决方法
原因
res.sendStatus(statusCode) 会直接发送带指定状态码的完整响应,同时结束整个响应流程。之后再调用.json()方法,会尝试再次设置响应头、发送响应体,这就触发了重复发送 HTTP 头的错误。
解决办法
根据实际需求二选一即可:
- 需要返回状态码+JSON数据的情况,用
res.status().json()替代:
app.post('/product', async (req, res) => { try { const singleProduct = await product.create(req.body) res.status(200).json(singleProduct) } catch (error) { console.log(error.message); res.status(500).json({ message: error.message }) } })
- 只需要返回状态码、不需要返回数据的情况,直接用
res.sendStatus()即可:
app.post('/product', async (req, res) => { try { await product.create(req.body) res.sendStatus(200) } catch (error) { console.log(error.message); res.sendStatus(500) } })
内容的提问来源于stack exchange,提问作者Shrutika Jaiswal
相关产品推荐
相关产品推荐

