Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 ;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

}

>Solution :

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().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading