Placement-ready Online Courses: Your Passport to Excellence - Start Now
Express.js is a web application framework for Node.js that provides a simple and flexible way to build web applications and APIs. One of the key features of Express.js is its powerful response system, which allows developers to send a wide range of responses to clients, including HTML, JSON, and other formats.
In this article, we’ll explore the various features of the Express.js response system and how to use them effectively in your web applications.
Express JS Response Object
In Express.js, the response object (res) is an object that represents the HTTP response that will be sent to the client. The res object is created automatically by the framework and is passed as an argument to route handler functions. Developers can use this object to set the response headers and body, and to send the response to the client.
Properties of Response Object of ExpressJS
Let’s take a look at some of the most commonly used properties of the Response object in Express:
1. res.statusCode
The res.statusCode property is a numeric HTTP status code indicating the status of the response. For example, a status code of 200 indicates that the request was successful, while a status code of 404 indicates that the requested resource was not found.
2. res.statusMessage
The res.statusMessage property is a string containing a human-readable status message corresponding to the numeric HTTP status code.
3. res.headersSent
The res.headersSent property is a Boolean value indicating whether the headers of the response have been sent to the client.
4. res.locals
The res.locals property is an object that contains variables that are local to the current request-response cycle. These variables can be used to pass data from middleware to routes or from routes to views.
Methods of the Response Object
In addition to the properties, the Response object also provides several useful methods:
1. res.send()
The res.send() method is used to send a response to the client. The method can take a variety of arguments, including a string, an object, an array, or a buffer. The method sets the appropriate headers for the response and sends the response back to the client.
app.get('/', (req, res) => {
res.send('Hello, World!');
});
2. res.json()
The res.json() method is used to send a JSON response to the client. The method takes an object or an array as an argument and sends it back to the client as a JSON-encoded response.
app.get('/users', (req, res) => {
const users = [{ name: 'John', age: 25 }, { name: 'Jane', age: 30 }];
res.json(users);
});
3. res.render()
The res.render() method is used to render a view and send the HTML response back to the client. The method takes the name of the view and an optional context object as arguments. Express uses a view engine to render the view.
app.get('/profile', (req, res) => {
const user = { name: 'John', age: 25 };
res.render('profile', { user });
});
4. res.redirect()
The res.redirect() method is used to redirect the client to a different URL. The method takes the URL as an argument and sends a 302 Found status code to the client, along with the Location header containing the new URL.
app.get('/login', (req, res) => {
if (!req.session.user) {
res.redirect('/login');
}
});
5. res.setHeader()
The res.setHeader() method is used to set an HTTP header on the response. The method takes the name of the header and its value as arguments.
app.get('/', (req, res) => {
res.setHeader('X-Powered-By', 'Express');
res.send('Hello, World!');
});
Key features of the res object in Express.js:
1. Setting Response Headers
The response headers are used to provide additional information about the response to the client, such as the content type, encoding, and caching information. In Express.js, you can set response headers using the set() method of the res object. Here’s an example:
app.get('/', function (req, res) {
res.set('Content-Type', 'text/html');
res.set('Cache-Control', 'public, max-age=300');
res.send('<h1>Hello World!</h1>');
});
In this example, we set the content type of the response to text/html and the caching information to public, max-age=300. The send() method is then used to send the HTML content to the client.
2. Sending Responses
In Express.js, you can send a response to the client using several methods of the res object, including send(), json(), and redirect(). Here’s a brief overview of each method:
a. send(): Sends the response body to the client. The content can be in any format, including HTML, plain text, or JSON.
b. json(): Sends a JSON response to the client. The input can be any JSON-serializable object.
c. redirect(): Redirects the client to a different URL.
Here are some examples of how to use these methods:
// Send a plain text response
app.get('/text', function (req, res) {
res.send('Hello World!');
});
// Send a JSON response
app.get('/json', function (req, res) {
res.json({ message: 'Hello World!' });
});
// Redirect to a different URL
app.get('/redirect', function (req, res) {
res.redirect('https://google.com');
});
3. Setting Response Status Codes
The HTTP status code is an important part of the response that indicates the status of the request. In Express.js, you can set the status code of the response using the status() method of the res object. Here’s an example:
app.get('/error', function (req, res) {
res.status(500).send('Internal Server Error');
});
In this example, we set the status code of the response to 500 (Internal Server Error) and send an error message to the client.
4. Rendering Views
In addition to sending plain text and JSON responses, Express.js also allows developers to render views (i.e., HTML templates) using templating engines such as EJS, Pug, and Handlebars. To render a view in Express.js, you can use the render() method of the res object. Here’s an example using EJS:
app.get('/view', function (req, res) {
res.render('index', { title: 'Hello World!' });
});
In this example, we use the render() method to render the index.ejs view template and pass in an object with the title property set to ‘Hello World!’. The templating engine will then use this object to populate the view with dynamic data.
ExpressJS response methods summarized
| Method | Description |
| res.attachment() | Sets the Content-Disposition header to “attachment” with the specified filename. The parameter is the filename to set. |
| res.clearCookie() | Clears a cookie in the HTTP response. The parameter is the name of the cookie to clear. |
| res.cookie() | Sets a cookie in the HTTP response. The first parameter is the name of the cookie, and the second parameter is the value. |
| res.download() | Sends a file as an attachment. The first parameter is the path of the file to send, and the second parameter is an optional filename. |
| res.end() | Ends the response process. |
| res.header() | Sets an HTTP response header. The first parameter is the name of the header, and the second parameter is the value. |
| res.json() | Sends a JSON response. This method is identical to res.send(), except that it sends a JSON-formatted response. |
| res.redirect() | Redirects the client to a new URL. The status code defaults to “302 Found”. |
| res.render() | Renders a view template with a set of data. The first parameter is the name of the view template, and the second parameter is an object containing data to be passed to the view template. |
| res.send() | Sends the HTTP response. The body parameter can be a Buffer object, a string, an object, or an array. |
| res.sendFile() | Sends a file as the HTTP response. The first parameter is the path of the file to send, and the second parameter is an optional options object. |
| res.status() | Sets the HTTP status code for the response. The parameter is the status code to set. |
| res.type() | Sets the content type of the response. The parameter is the content type to set. |
Conclusion
In this article, we’ve explored the various features of the Express JS response system and how to use them effectively in your web applications. We’ve seen how to set response headers, send responses in different formats (e.g., HTML, JSON), set response status codes, and render views using templating engines.
By leveraging the powerful response system provided by Express.js, you can create web applications that are both flexible and efficient, and that can handle a wide range of client requests. Whether you’re building a simple website or a complex API, Express.js provides a robust and intuitive framework for creating powerful web applications.
