The response object
The response object res is the second argument of a handler. Through it the server tells the client the status code, the headers and the response body. A status code is a number that tells the client the result: 200 — success, 404 — not found, 500 — server error.
Text and HTML
res.send() sends a string. If the string looks like HTML, the browser shows it as a page:
// src/app.js
app.get('/about', (req, res) => {
res.send('<h1>About the blog</h1><p>We write about Express.</p>');
});http://localhost:3000/about shows a heading and a paragraph. Express sets the Content-Type: text/html header itself.
JSON
res.json() turns an object or an array into JSON and sets the Content-Type: application/json header:
// src/app.js
import { posts } from './data/posts.js';
app.get('/api/posts', (req, res) => {
res.json(posts);
});At /api/posts the browser shows the array of posts as JSON. This is how you answer programs, not people.
Status code
By default the code is 200. res.status() changes it and returns the same res, so the calls are chained:
// src/app.js
app.get('/api/posts/:id', (req, res) => {
const post = posts.find((item) => item.id === Number(req.params.id));
if (!post) {
return res.status(404).json({ error: 'Post not found' });
}
res.json(post);
});If no body is needed, use res.sendStatus(204) — it sends only the code.
Redirect
res.redirect() sends the browser to another address. The default code is 302, "found elsewhere for now":
// src/app.js
app.get('/blog', (req, res) => {
res.redirect('/posts');
});
app.get('/old-posts', (req, res) => {
res.redirect(301, '/posts');
});Open /blog and the address bar changes to /posts at once. Code 301 says the address has changed permanently, and search engines remember the new one.
Methods at a glance
| Method | What it does |
|---|---|
res.send(text) | Sends text or HTML |
res.json(data) | Sends JSON |
res.status(code) | Sets the status code, sends nothing |
res.sendStatus(code) | Sends only the code |
res.redirect(url) | Redirects to another address |
res.set(name, value) | Sets a header |
res.render(view, data) | Sends a page built from a template |
res.sendFile(path) | Sends a file |
Common mistake
Only one response can be sent per request. If the code keeps running after res.json() and responds again, Express throws Cannot set headers after they are sent to the client. Put return before a response after which the handler must stop, as in the 404 example. And remember that res.status(404) sends nothing by itself: it must be followed by send() or json().