I'm a beginner in Express.js
and I'm confused by these two keywords: res.end()
and res.send()
.
Are they the same or different?
end() Method. Express JSServer Side ProgrammingProgramming. The res. end() method ends the current response process. This method is used to quickly end the response without any data.
basically, res. send is for express and res. write+res. end() is for bare metal node ways to send data.
send function sets the content type to text/Html which means that the client will now treat it as text. It then returns the response to the client. The res. json function on the other handsets the content-type header to application/JSON so that the client treats the response string as a valid JSON object.
No, it's not necessary to call res. end() after you have called res. json() (or res.
First of all, res.send()
and res.end()
are not the same.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With