In Express.js, response methods are crucial for controlling how data is returned to the client. These methods provide various ways to respond to HTTP requests, such as sending JSON data, redirecting the client, or serving a file. In this tutorial, you will explore response methods in Express.js and learn how to use them effectively.
Response Methods in Express.js
Express.js offers a rich set of response methods through the response object (res
), making it easy to handle HTTP responses:
res.send()
res.json()
res.sendFile()
res.status()
res.redirect()
res.render()
res.set()
res.end()
res.format()
res.send()
The res.send()
method sends the response body to the client, which can be a string, buffer, or object. It also automatically sets the content type based on the input type.
Example:
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
In the above example, the plain text "Hello, Express!" is sent as a response when a GET request is made to the root URL. Express automatically sets the Content-Type
to text/html
.
res.json()
The res.json()
method is designed to send a JSON response. It automatically converts objects or arrays into JSON format and sets the Content-Type
header to application/json
.
Example:
app.get('/user', (req, res) => {
res.json({ name: 'Alex', age: 30 });
});
This res.json
method is commonly used for API responses where the server needs to send structured data in JSON format.
res.sendFile()
The res.sendFile()
method sends a file as a response. It requires an absolute path to the file on the server.
Example:
const path = require('path');
app.get('/download', (req, res) => {
const filePath = path.join(__dirname, 'files', 'example.pdf');
res.sendFile(filePath);
});
In the above example, a PDF file in the server's files
directory is sent to the client when they visit the /download
endpoint. This method automatically sets the appropriate content type for the file being served.
res.status()
The res.status()
method sets the HTTP status code for the response. You can chain it with other response methods like res.send()
or res.json()
to specify the status code along with the data.
Example:
app.get('/error', (req, res) => {
res.status(404).send('Page Not Found');
});
The above example sends the client a 404 "Page Not Found" message, indicating that the requested resource does not exist.
res.redirect()
The res.redirect()
method sends a redirect response, instructing the client to navigate to a different URL.
Example:
app.get('/old-page', (req, res) => {
res.redirect('/new-page');
});
When the client accesses /old-page
, they will be redirected to /new-page
.
You can also pass a status code to specify whether the redirect is permanent (301) or temporary (302, default):
Example:
app.get('/temp-redirect', (req, res) => {
res.redirect(302, '/temporary');
});
res.render()
The res.render()
method renders a view template (e.g., EJS, Pug, Handlebars) and sends the resulting HTML to the client.
Example:
app.set('view engine', 'ejs');
app.get('/profile', (req, res) => {
const user = { name: 'Anjali', age: 25 };
res.render('profile', { user });
});
In the above example, the server renders an EJS template called profile.ejs
with the provided user data, which is then sent to the client as HTML.
res.set()
The res.set()
method sets HTTP headers for the response. It's useful when you need to modify or add headers.
Example:
app.get('/setheader', (req, res) => {
res.set('Content-Type', 'text/html');
res.send('<h1>Header Set</h1>');
});
In the above example, the Content-Type
header is set to text/html
, and the HTML content is sent in the response.
res.end()
The res.end()
method ends the response process without sending any data. It's useful when you need to control the flow manually.
Example:
app.get('/end', (req, res) => {
res.status(204).end();
});
In the above example, a response with no content (status code 204) is sent, and the response process ends.
res.format()
The res.format()
method allows you to send different responses based on the client's Accept
header. It's useful for content negotiation, where clients expect different content types.
Example:
app.get('/format', (req, res) => {
res.format({
'text/plain': () => {
res.send('Plain text response');
},
'text/html': () => {
res.send('<p>HTML response</p>');
},
'application/json': () => {
res.json({ message: 'JSON response' });
}
});
});
The above example code sends different responses depending on the client's Accept
header.
Conclusion
In this tutorial, you have explored the most commonly used response methods in Express.js, including res.send()
, res.json()
, res.status()
, and more. These methods allow you to effectively handle various HTTP responses, whether you're sending data, files, or redirecting users. Understanding these methods is essential for building dynamic web applications that communicate properly with clients.