Home > Software engineering >  Using res.write before res.send results in error
Using res.write before res.send results in error

Time:11-03

I'm trying to understand why the following code throws an error.

app.get("/", (req, res) => {
    res.write("Hello");
    res.send(" World!");
})
// Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

app.get("/", (req, res) => {
    res.write("Hello");
    res.write(" World!");
    res.end();
})
// Works fine

I don't see how headers are set after res.send since res.send is the one who sets the headers.

I read online that res.send is the equivalent of res.write res.end, but this shows it is not entirely true.

I would like to be able to write base data to the response and then use res.send for it's useful task like automatically setting the Content-Type header based on the data sent.

app.use((req, res, next) => {
    res.write("Base data");
    next();
})

app.get("/", (req, res) => {
    res.send("Route specific data");
})
// Result: Base data   Route specific data

Is there something other than res.write which lets me write data to the response but doesn't conflict with res.send ?

CodePudding user response:

res.write starts writing the body, but before it can do so, it must write all headers, and you cannot write any additional headers afterwards. But res.send writes an additional Content-Type header, based on whether its argument is a Javascript object or a a string. Therefore you cannot use res.send after res.write.

res.send is meant to be used on its own, like res.json or res.render.

  • Related