Send HTML text
A route returns a rendered or markup-like response directly to the client.
Express.js · Function
Sends an HTTP response from an Express route or middleware. Express formats strings as HTML, objects and arrays as JSON, and buffers as binary data.
Call res.send(body) inside a route handler to complete the HTTP response. Express selects the response representation from the value: strings are treated as HTML, objects and arrays as JSON, and buffers as binary data; the method returns the response object for chaining.
res.send(body)| Name | Type | Description |
|---|---|---|
body | String | Buffer | Object | Array | Boolean | undefined | The response content. Strings are sent as HTML, objects and arrays as JSON, and buffers as binary data; the documented type also includes Boolean and undefined. |
Response
res.status(code).send(body).res.status(status).send(body) instead.res.sendStatus() when the response should contain only a status code.String(value).const express = require('express');
const app = express();
app.get('/user/:id', (req, res) => {
res.send(`user ${req.params.id}`);
});
app.listen(3000);Creates a route that sends a string response for a requested user ID.
A route returns a rendered or markup-like response directly to the client.
An endpoint returns structured application data without manually serializing it.
A handler needs to transmit already-created binary content.
res.send() do, and what body types does it accept?res.send(body) sends the HTTP response and returns the Response object. Express treats strings as HTML, objects and arrays as JSON, and buffers as binary data.
Follow-up: How would you return a JSON error with a non-200 status? Chain the status setter: res.status(500).send({ error: 'something blew up' }).
The documented body argument may be a string, buffer, object, array, boolean, or undefined. The method chooses handling based on the supplied value, including HTML for strings and JSON for objects or arrays.
Follow-up: What should be done with a numeric body? Convert it to a string first, such as res.send(String(123)), so it is not treated as a status code.
res.send()?Set the status separately by chaining res.status(status).send(body). The older positional forms are deprecated, including res.send(body, status) and res.send(status) in Express 4.5.0, with the reversed form deprecated in 4.7.0.
Follow-up: Which method sends only a status code? Use res.sendStatus(status).
res.status()res.sendStatus()res.json()res.end()