头图

foreword

In Node.js , if the Express framework is used, there are often two responses to a request:

// 方法1
app.get("/end", (req, res, next) =>{
    res.end(xxx);
});
// 方法2
app.get("/send", (req, res, next) =>{
    res.send(xxx);
});

So what is the difference between these two methods? What are their respective application scenarios? This is what I need to make clear today.

Res.end() of Express

definition

It can quickly end the response without requiring any data.

This method is actually from the Node core, specifically http.ServerResponse.Use of response.end() method:

image-20220121021236372

grammar

res.end([data[, encoding]][, callback])

Parameter parsing:

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

in-depth

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

image-20220121012102733

Res.send() of Express

definition

Send an HTTP response message to the requesting client.

grammar

res.send([body[,statusCode]])

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

in-depth

By debugging the code, we can find, Express is res.send() is the final method called http.ServerResponse.Use of response.end() method:

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

Compared

Same point

Express's res.end() and res.send() methods are identical:

  1. Both are ultimately return to http.ServerResponse.Use of response.end() method.
  2. Both will end the current response process.

difference

Differences between Express's res.end() and res.send() methods:

  1. The former can only send string or Buffer types, the latter can send any type of data.
  2. From a semantic point of view, the former is more suitable for scenarios without any response data, while the latter is more suitable for scenarios with response data.

Summarize

When using the res.end() and res.send() methods of Express, it is generally recommended to use the res.send() method, so that you don't need to care about the format of the response data, because Express processes the data internally.

~

~End of this article, thanks for reading!

~

Learn interesting knowledge, meet interesting friends, and shape interesting souls!

Hello everyone, I'm King , the author Programming Samadhi 〗, my public is "161f218cadae83 Programming Samadhi ", welcome to pay attention, I hope you can give me more advice!

You come, with expectations, I have the fragrance of ink to welcome you! You return, no matter what you gain or lose, you can only give it away with the aftertaste!

Both knowledge and skills are emphasized, internal and external skills are cultivated, both theory and practice must be grasped, and both hands must be hard!


编程三昧
54 声望10 粉丝

学习有趣的知识,交识有趣的朋友,造就有趣的灵魂!