Return API data
An API endpoint returns a resource or collection as JSON.
Express.js · Function
res.json(body) serializes a value as JSON, sets the appropriate content type, and sends the response. Set a non-default status with res.status(code).json(body) rather than a deprecated positional status argument.
Call res.json(body) in a route to serialize the supplied value with JSON.stringify(), set the appropriate content type, and send the response. Chain res.status(code) first when the response needs a non-default status.
res.json([body])| Name | Type | Description |
|---|---|---|
body | any | undefined | The value to serialize and send. It may be an object, array, string, Boolean, number, or null. |
status | Number | undefined | Deprecated positional HTTP status code; use res.status() instead. |
Response
res.json() is a response method for sending JSON to the client.JSON.stringify() before transmission.res.status(code).json(body).const express = require('express');
const app = express();
app.get('/user', (req, res) => {
res.status(200).json({ id: 7, name: 'Ada' });
});
app.listen(3000);This route sends a JSON object with an explicit successful HTTP status.
An API endpoint returns a resource or collection as JSON.
A handler needs to report an error payload with a specific HTTP status.
A route returns a primitive or null value that still needs JSON serialization.
res.json() do?res.json(body) converts the supplied value to a JSON string with JSON.stringify(), sends it, and uses the correct content type. The body may be an object, array, string, Boolean, number, or null.
Follow-up: How should a 201 response be sent? Use res.status(201).json(body) rather than a deprecated positional status argument.
res.json() return?The method returns the Express Response object. That allows response methods such as status() to be chained around the JSON send operation.
Follow-up: What is the modern replacement for res.json(body, 500)? Use res.status(500).json(body).
The documented method accepts a body value and an older status positional argument. The status argument is deprecated, so status should be configured through res.status() instead.
Follow-up: Which older signatures are deprecated? res.json(obj, status) since v4.2.0 and res.json(status, obj) since v4.7.0.
res.send()res.status()res.jsonp()res.sendStatus()