In Express.js, response methods are used to send responses back to the client that made the request. Response methods are invoked on the res
object, which is the second argument in the route handler function. The response methods are used to send a response, redirect the user to another URL, or to render a view.
Response methods in Express.js
res.send()
This method sends a response to the client with the data that is passed to it. It can be used to send a string, JSON, or HTML.
Example:
app.get('/hello', function(req, res) {
res.send('Hello World!');
});
res.json()
This method sends a JSON response to the client with the data that is passed to it.
Example:
app.get('/users', function(req, res) {
res.json({
name: 'John Doe',
email: '[email protected]'
});
});
res.render()
This method is used to render a view template and send the HTML to the client. The view engine used can be specified in the Express.js app configuration.
Example:
app.get('/profile', function(req, res) {
res.render('profile', { name: 'John Doe', email: '[email protected]' });
});
res.redirect()
This method is used to redirect the client to another URL.
Example:
app.get('/google', function(req, res) {
res.redirect('http://www.google.com');
});
res.status()
This method is used to set the HTTP status code of the response.
Example:
app.get('/not-found', function(req, res) {
res.status(404).send('Sorry, page not found');
});
These are some of the commonly used response methods in Express.js. There are many more response methods available, and you can also create custom response methods if you need to.
res.sendFile()
This method sends a file as the response to the client.
Example:
app.get('/download', function(req, res) {
res.sendFile('/path/to/file.pdf');
});
res.set()
This method is used to set the HTTP headers of the response.
Example:
app.get('/custom-headers', function(req, res) {
res.set('Cache-Control', 'public, max-age=300, s-maxage=600');
res.send('Custom headers set');
});
res.type()
This method is used to set the content type of the response.
Example:
app.get('/image', function(req, res) {
res.type('png');
res.send('/path/to/image.png');
});
res.cookie()
This method is used to set a cookie in the response.
Example:
app.get('/set-cookie', function(req, res) {
res.cookie('name', 'John Doe');
res.send('Cookie set');
});
res.clearCookie()
This method is used to clear a cookie in the response.
Example:
app.get('/clear-cookie', function(req, res) {
res.clearCookie('name');
res.send('Cookie cleared');
});
These are some more commonly used response methods in Express.js. By using these methods, you can send the appropriate response to the client based on the request that was made.
res.attachment()
This method is used to set the Content-Disposition
header to attachment
, which prompts the user to download the file rather than displaying it in the browser.
Example:
app.get('/download-pdf', function(req, res) {
res.attachment('/path/to/file.pdf');
res.send('Download PDF');
});
res.format()
This method is used to send different responses based on the Accept
header of the request. It takes an object that specifies the content type and response handler for each possible response.
Example:
app.get('/users', function(req, res) {
res.format({
'text/plain': function() {
res.send('John Doe\nJane Smith');
},
'application/json': function() {
res.json([
{ name: 'John Doe', email: '[email protected]' },
{ name: 'Jane Smith', email: '[email protected]' }
]);
},
'default': function() {
res.send(406, 'Not Acceptable');
}
});
});
res.end()
This method is used to end the response process. It can be useful if you need to perform some final cleanup or logging after sending the response.
Example:
app.get('/logout', function(req, res) {
req.logout();
res.end();
console.log('User logged out');
});
res.sendfile()
This method is used to send a file as the response to the client. It is similar to res.sendFile()
, but with additional options such as specifying the headers to send with the file.
Example:
app.get('/download', function(req, res) {
res.sendfile('/path/to/file.pdf', { headers: { 'X-Custom-Header': 'Custom Value' }});
});
res.type()
This method is used to set the Content-Type
header of the response.
Example:
app.get('/image', function(req, res) {
res.type('png');
res.send('/path/to/image.png');
});
res.links()
This method is used to set the Link
header of the response. This header is used to indicate relationships between resources.
Example:
app.get('/related-resources', function(req, res) {
res.links({
next: 'http://example.com/page2',
last: 'http://example.com/page10'
});
res.send('Related resources');
});
res.location()
This method is used to set the Location
header of the response, which is used for redirects.
Example:
app.get('/redirect', function(req, res) {
res.location('http://example.com/new-location');
res.send('Redirecting');
});
These are a few more response methods in Express.js that you can use to customize the response that you send to the client.
I must say, this article on response methods in Express.js is a gem! As an experienced Node.js developer, I’ve used Express.js extensively, but your comprehensive explanation of the response methods gave me new insights. I particularly liked the examples showcasing res.send() and res.json(). The comparison between res.send() and res.json() cleared up any confusion I had. Thank you for sharing your expertise!
Thank you for this informative guide! As a beginner in Express.js, I struggled to understand the different response methods available. Your article explained each method clearly and provided practical use cases. The explanation of res.redirect() and res.sendFile() was particularly helpful. I feel more confident in handling responses now. Keep up the excellent work!
I wanted to respond to a previous comment. I agree that this guide is incredibly valuable for understanding response methods in Express.js. However, I believe you missed mentioning the res.status() method, which is useful for setting the HTTP status code in the response. Including that information would make the guide more comprehensive. Other than that, your article was well-written and informative!
Express.js is my go-to framework for web development, and this article on response methods in Express.js added to my knowledge. The explanations were clear, and the code samples were practical. I now have a better understanding of handling responses in my Express.js applications. Great job!