Express Response JSON

Sep 13, 2019

Express response objects have a json() function. The res.json() function takes a single parameter, an object obj, serializes it to JSON, and sends it in the HTTP response body.

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

app.get('*', function(req, res) {
  res.json({ answer: 42 });
});

const server = await app.listen(3000);

const response = await axios.get('http://localhost:3000');
response.data; // { answer: 42 }
response.headers['content-type']; // 'application/json; charset=utf-8'

Express also sets the content-type header to application/json. Most HTTP clients, like Axios, handle automatically transforming JSON strings into JavaScript objects using JSON.parse() when the content type is application/json.

The res.json() uses JSON.stringify() under the hood to serialize objects into JSON. You can configure the arguments that Express passes to JSON.stringify() using app.use(). For example, to make Express pretty print JSON, you can use app.set('json spaces', 2) as shown below.

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

// Make Express pass '2' as the 3rd argument to `JSON.stringify()`
app.set('json spaces', 2);

app.get('*', function(req, res) {
  res.json({ answer: 42, hello: 'world' });
});

const server = await app.listen(3000);

const response = await axios.get('http://localhost:3000', {
  transformResponse: res => res // Disable automatic JSON parsing
});
// {
//   "answer": 42,
//   "hello": "world"
// }
response.data;

More Express Tutorials