In addition to the excellent answers, I would like to emphasize here when to use res.end() and when to use res.send() this was why I originally landed here and I didn't found a solution.
The answer is really simple
res.end() is used to quickly end the response without sending any data.
An example for this would be starting a process on a server
app.get(/start-service, (req, res) => {
// Some logic here
exec('./application'); // dummy code
res.end();
});
If you would like to send data in your response then you should use res.send() instead
app.get(/start-service, (req, res) => {
res.send('{"age":22}');
});
Here you can read more
res
is an HttpResponse object which extends from OutgoingMessage. res.send
calls res.end
which is implemented by OutgoingMessage to send HTTP response and close connection. We see code here
res.send()
implements res.write
, res.setHeaders
and res.end
:
res.write
.res.end
to set the end of the request.There are some cases in which you will want to do this manually, for example, if you want to stream a file or a large data set. In these cases, you will want to set the headers yourself and use res.write
to keep the stream flow.
I would like to make a little bit more emphasis on some key differences between res.end()
& res.send()
with respect to response headers and why they are important.
1. res.send() will check the structure of your output and set header information accordingly.
app.get('/',(req,res)=>{
res.send('<b>hello</b>');
});
app.get('/',(req,res)=>{
res.send({msg:'hello'});
});
Where with res.end() you can only respond with text and it will not set "Content-Type"
app.get('/',(req,res)=>{
res.end('<b>hello</b>');
});
2. res.send() will set "ETag" attribute in the response header
app.get('/',(req,res)=>{
res.send('<b>hello</b>');
});
¿Why is this tag important?
The ETag HTTP response header is an identifier for a specific version of a resource. It allows caches to be more efficient, and saves bandwidth, as a web server does not need to send a full response if the content has not changed.
res.end()
will NOT set this header attribute
res.send
is used to send the response to the client where res.end
is used to end the response you are sending.
res.send
automatically call res.end
So you don't have to call or mention it after res.send
Source: Stackoverflow.com