ReasonJun

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

Backend/Express.js

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

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

The res.json() 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.json() sends the data in JSON format. This is the preferred format for sending data between applications, as it is both human-readable and machine-readable.
  • res.send() can send data in any format. This includes JSON, HTML, images, and other types of data.
  • res.json() automatically sets the Content-Type header to application/json. This tells the client that the data is in JSON format.
  • res.send() does not automatically set the Content-Type header. You must set it manually if you want to send data in a format other than JSON.
  • res.json() can also be used to convert non-JSON objects to JSON. This is useful if you want to send data that is not a valid JSON object, such as a null or an undefined value.

In general, you should use res.json() if you want to send data in JSON format. However, you can use res.send() if you need to send data in a different format, or if you do not want to automatically set the Content-Type header.

 

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

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

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

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

This code will send a JSON object with the message "Hello, world!" back to the client.

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 in its original format.

728x90

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

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