Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the difference between res.send () and res.end () in node Express framework

Shulou Source: shulou.com Published: 2022-06-01 17:53:08 12月03日 Update

This article mainly explains "what is the difference between res.send() and res.end() in the node Express framework". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. What is the difference between res.send() and res.end() in the node Express framework?

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

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

So what is the difference between these two ways? What are their respective application scenarios? That's what I need to make clear today.

res of Express.end()

defined

It can end up responding quickly without needing any data.

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

syntax

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

Parameter analysis:

data |

encoding

callback

in-depth

If you pass an object to the res.end() method, an error occurs:

res of Express.send()

defined

Send HTTP response message to requesting client.

syntax

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

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

in-depth

Through code debugging, we can find that the res.send() method of Express finally calls the response.end() method of http.ServerResponse.Use:

// node_modules/express/lib/response.jsres.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;}; Compare

same point

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

Both ultimately revert to the response.end() method of http.ServerResponse.Use.

Both end the current response flow.

different points

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

The former can only send string or Buffer types, while the latter can send any type of data.

Semantically, the former is better suited to scenarios without any response data, while the latter is better suited to scenarios with response data.

At this point, I believe that everyone has a deeper understanding of "res.send() and res.end() in the node Express framework." Let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

Tags: Methods frameworks data scenarios different same different points code content parameters actual way similarities types syntax learning practical deeper interest practicality Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Redmi Xiaomi macOS Shulou Tech Info