Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between res.end() and res.send()?

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?

like image 653
sudheeshcm Avatar asked Oct 18 '22 04:10

sudheeshcm


People also ask

What res end () does?

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.

What is the difference between Res send and RES write?

basically, res. send is for express and res. write+res. end() is for bare metal node ways to send data.

What is the difference between Res send and RES json?

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.

Does Res json end the request?

No, it's not necessary to call res. end() after you have called res. json() (or res.


1 Answers

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>');
    });

enter image description here


     app.get('/',(req,res)=>{
         res.send({msg:'hello'});
     });

enter image description here

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>');
      }); 

enter image description here

2. res.send() will set "ETag" attribute in the response header

      app.get('/',(req,res)=>{
            res.send('<b>hello</b>');
      });

enter image description here

¿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

like image 242
Jorge González Avatar answered Oct 19 '22 16:10

Jorge González