Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between res.send and res.write in express?

I am a beginner to express.js and I am trying to understand the difference between res.send and res.write ?

like image 481
P G Avatar asked Jun 22 '17 06:06

P G


People also ask

What is difference between Res send and res end?

res. send() is used to send the response to the client where res. end() is used to end the response you are sending.

What is the difference between Res send and RES json in Express?

There is no actual difference between res. send and res. json, both methods are almost identical.

What is RES send in Express?

send() function basically sends the HTTP response. The body parameter can be a String or a Buffer object or an object or an Array. Syntax: res.send( [body] ) Parameter: This function accepts a single parameter body that describe the body which is to be sent in the response.

What happens after Res send?

res. send() or res. json() should end all writing to the response stream and send the response. However, you absolutely can call next() if you want to do further processing after the response is sent, just make sure you don't write to the response stream after you call res.


1 Answers

res.send

  • res.send is only in Express.js.
  • Performs many useful tasks for simple non-streaming responses.
  • Ability to automatically assigns the Content-Length HTTP response header field.
  • Ability to provides automatic HEAD & HTTP cache freshness support.
  • Practical explanation
    • res.send can only be called once, since it is equivalent to res.write + res.end()
    • Example:
      app.get('/user/:id', function (req, res) {     res.send('OK'); }); 

For more details:

  • Express.js: Response

res.write

  • Can be called multiple times to provide successive parts of the body.
  • Example:
    response.write('<html>'); response.write('<body>'); response.write('<h1>Hello, World!</h1>'); response.write('</body>'); response.write('</html>'); response.end(); 

For more details:

  • response.write(chunk[, encoding][, callback])
  • Anatomy of an HTTP Transaction: Sending Response Body
like image 107
Omal Perera Avatar answered Sep 26 '22 06:09

Omal Perera