mongoose 显示错误:错误[ERR_HTTP_HEADERS_SENT]:在将头发送到终端上的客户端后,无法设置头

3xiyfsfu  于 2023-05-13  发布在  Go
关注(0)|答案(1)|浏览(147)

Node.js版本:v18.15.0 mongoose:7.1.1
当我通过PostMan发送数据时,它很好地保存了所有内容并完成了它的工作,但我在控制台上得到了这个错误。

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 })
    }

通过 Postman 投递数据后,显示以下错误

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'
}
mo49yndu

mo49yndu1#

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(401).json({ message: error.message })
}

相关问题