Console gives me Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

huangapple go评论93阅读模式
英文:

Console gives me Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

问题

我不知道如何修复这个错误。

但是当我通过 PostMan 发送数据时,它能够保存所有数据并正常工作,但在控制台上会出现这个错误。
如果我移除 .json(table).end(),它就能正常工作。

英文:

I don't know how to fix this error.

But when I send data through PostMan, it saves everything well and does its job, but I get this error on the console.
If I remove the .json(table).end() it works.

export const build_tab = async (req : express.Request , res : express.Response ) => {
try{
const { seats, number } = req.body ;

    if(!seats||!number){
       return res.sendStatus(400);
    }
    const _id = require('uuid').v4() ;
   
    const table = await createTable({
        _id,
        number,
        seats
    });

    return res.sendStatus(200).json(table).end();
}
catch(error){
   console.log(error)         ;
   return res.sendStatus(400) ;
}

}

答案1

得分: 1

res.sendStatus(<code>)不应与任何其他Express函数链接,因为它会设置状态并单独发送响应主体。
请参阅文档

将响应的HTTP状态代码设置为statusCode,并将注册的状态消息发送为文本响应主体。如果指定了未知的状态代码,则响应主体将只包含代码号。

因此,如果您想发送自定义的JSON主体,请不要使用.sendStatus()。而是使用类似以下的方法:

return res.status(200).json(table)

请注意,您不需要在.json(...)后使用.end()。关于.end()文档如下:

用于快速结束响应而不包含任何数据。如果需要响应数据,请改用res.send()res.json()等方法。

英文:

res.sendStatus(<code>) isn't meant to be chained with any other express functions because it sets the status and sends a response body all by itself.
See the documentation:

> Sets the response HTTP status code to statusCode and sends the registered status message as the text response body. If an unknown status code is specified, the response body will just be the code number.

Therefore, if you want to send a custom json body, don't use .sendStatus(). Instead, just use something like:

return res.status(200).json(table)

Note that you don't need to follow .json(...) with .end(). Here is the documentation for .end():
> Use to quickly end the response without any data. If you need to respond with data, instead use methods such as res.send() and res.json().

huangapple
  • 本文由 发表于 2023年7月28日 03:25:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76782838.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定