“This is my fourth day of participating in the First Challenge 2022. For more details: First Challenge 2022.”

preface

In server-side code using Node.js, if you are using the Express framework, there are usually two ways to respond to a request:

1 / / method
app.get("/end".(req, res, next) = >{
    res.end(xxx);
});
2 / / method
app.get("/send".(req, res, next) = >{
    res.send(xxx);
});
Copy the code

So what’s the difference between these two approaches? What are the application scenarios? That’s what I need to make clear today.

Express the res. End ()

define

It can quickly end a response without requiring any data.

This method actually comes from the Node core, specifically the response.end() method of http.serverResponse.use:

grammar

res.end([data[, encoding]][, callback])
Copy the code

Parameter analysis:

  • data <string> | <Buffer>
  • encoding <string>
  • callback <Function>

in-depth

If an object is passed to the res.end() method, an error occurs:

Express the res of the send ()

define

Send an HTTP response message to the requesting client.

grammar

res.send([body[,statusCode]])
Copy the code

The body argument can be Buffer, Object, String, Boolean, or Array.

in-depth

Express res.send() also calls http.serverResponse.use response.end() :

// node_modules/express/lib/response.js
res.send = function send(body) {
  var chunk = body;
  varencoding; ...if (req.method === 'HEAD') {
    // skip body for HEAD
    this.end();
  } else {
    // respond
    this.end(chunk, encoding);
  }
  return this;
};
Copy the code

contrast

The same

The res.end() and res.send() methods of Express are similar:

  1. Both end up going back tohttp.ServerResponse.Useresponse.end()Methods.
  2. Both end the current response process.

The difference between

The res.end() and res.send() methods of Express differ:

  1. The former can only send string or Buffer, while the latter can send any type of data.
  2. Semantically, the former is more suitable for scenarios where there is no response data at all, while the latter is more suitable for scenarios where there is response data.

conclusion

When using the Res.end () and res.send() methods of Express, it is generally recommended to use res.send(). This way, you do not need to care about the format of the response data because the data is processed internally in Express.

~

Thanks for reading!

~

Learn interesting knowledge, meet interesting friends, shape interesting soul!

Hello everyone, I am the author of “programming Samadhi”, I am king Yi, my public account is “programming Samadhi”, welcome to pay attention, I hope you can give me more advice!

You come, with expectations, I have ink to welcome! You return, no matter gain or loss, only to yu Yun give each other!

Knowledge and skills should be paid equal attention to, internal force and external power should be repaired simultaneously, theory and practice should grasp both hands, both hands should be hard!