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 ?