Express Response Object
The response object, abbreviated as res, gives you methods to send a response back to the client. You call one of these methods at the end of every route handler.
Response methods
res.send(): send any data (text, HTML, or an object)res.json(): send a JSON responseres.status(): set the HTTP status code (chainable)res.redirect(): redirect to a different pathres.render(): render a view templateres.sendFile(): send a file
res.send()
Sends a response with any content type. Express detects the type automatically.
app.get('/', (req, res) => {
res.send({ people: ['Anna', 'John'] }); // sends JSON
res.send('<h1>Hello World</h1>'); // sends HTML
res.send('Normal text'); // sends plain text
});
res.json()
Sends a JSON response and sets the Content-Type header to application/json. Prefer this over res.send() when returning JSON from an API.
app.get('/api/users', (req, res) => {
res.json({ people: ['Anna', 'John'] });
});
res.status()
Sets the HTTP status code. It is chainable, so you can combine it with res.json() or res.send():
app.get('/not-found', (req, res) => {
res.status(404).json({ error: 'Not found' });
});
app.get('/error', (req, res) => {
res.status(500).send('Internal server error');
});
Status code ranges:
- 1xx: informational
- 2xx: success
- 3xx: redirects
- 4xx: client errors
- 5xx: server errors
res.redirect()
Redirects the client to a different URL. Express sets the status code automatically (302 by default):
app.get('/old-path', (req, res) => {
res.redirect('/new-path');
});
res.render()
Renders a view template and sends the resulting HTML. Requires a view engine to be set up. See View Engines for details.
res.sendFile()
Sends a file. By default it requires an absolute path, so pass { root: __dirname } for relative paths:
app.get('/', (req, res) => {
res.sendFile('./views/index.html', { root: __dirname });
});
Practical examples
Sending simple HTML
const express = require('express');
const app = express();
app.listen(3000);
app.get('/', (req, res) => {
res.send('<p>Home page</p>');
});
app.get('/about', (req, res) => {
res.send('<p>About page</p>');
});
Sending HTML files
const express = require('express');
const app = express();
app.listen(3000);
app.get('/', (req, res) => {
res.sendFile('./views/index.html', { root: __dirname });
});
app.get('/about', (req, res) => {
res.sendFile('./views/about.html', { root: __dirname });
});
Redirects and 404
// Redirect /about-us to /about
app.get('/about-us', (req, res) => {
res.redirect('/about');
});
// 404 handler: must be last, after all other routes
app.use((req, res) => {
res.status(404).sendFile('./views/404.html', { root: __dirname });
});
What to read next
- Request Object : read data from the incoming request
- Routing : define which routes call which handlers