1

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 ?

  • Does this answer your question? [What is the difference between res.send and res.write in express?](https://stackoverflow.com/questions/44692048/what-is-the-difference-between-res-send-and-res-write-in-express) – GrafiCode Nov 02 '22 at 15:47
  • https://expressjs.com/en/api.html#res.send The docs explicitly tell you this -> `This method performs many useful tasks for simple non-streaming responses:` – Keith Nov 02 '22 at 15:49

1 Answers1

2

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.

Heiko Theißen
  • 12,807
  • 2
  • 7
  • 31
  • Reading from the docs, I thought I couldn't change headers after res.end, but it really is after writing to the body. Thanks – Hello World Nov 03 '22 at 07:30