ReasonJun

Express.js : res.end() / res.send() 본문

Backend/Express.js

Express.js : res.end() / res.send()

ReasonJun 2023. 9. 4. 15:18
728x90

The res.end() and res.send() methods in Express.js are both used to send data back to the client. However, there are some key differences between the two methods.

  • res.end() only sends the data that is passed to it. It does not set any headers or end the response.
  • res.send() sends the data that is passed to it, and it also sets the Content-Type header to the appropriate value. It also ends the response.

In other words, res.end() is a more lightweight method that is only used to send data. res.send() is a more comprehensive method that is used to send data and also set headers and end the response.

Here is an example of how to use res.end():

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.end('Hello, world!');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

This code will send the string "Hello, world!" back to the client, but it will not set any headers or end the response.

Here is an example of how to use res.send():

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello, world!');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

This code will send the string "Hello, world!" back to the client, and it will also set the Content-Type header to text/plain. The response will also be ended.

 

Summary : 

  • res.end()
    • Only sends the data that is passed to it.
    • Does not set any headers.
    • Does not end the response.
    • This means that you are responsible for setting the headers and ending the response yourself.
    • This can be useful if you want to send data in a format other than JSON, or if you want to set custom headers.
  • res.send()
    • Sends the data that is passed to it.
    • Sets the Content-Type header to the appropriate value.
    • Ends the response.
    • This is the simplest way to send data back to the client. It is also the most common way to send JSON data.

In general, you should use res.send() unless you have a specific reason to use res.end().

Here is a table that summarizes the key differences between res.end() and res.send():

Feature res.end() res.send()
Sends data Yes Yes
Sets headers No Yes
Ends response No Yes
When to use When you need to send data in a format other than JSON, or when you want to set custom headers When you want to send JSON data or when you do not need to set custom headers
728x90

'Backend > Express.js' 카테고리의 다른 글

Express.js : MVC Pattern  (0) 2023.09.04
Express.js : Middleware  (0) 2023.09.04
Express.js : res.json() / res.send()  (0) 2023.09.04
Express.js : Concept  (0) 2023.09.04
Comments