Express.js utilizes request and response objects to handle incoming HTTP requests and outgoing HTTP responses. These objects are essential for managing interactions in developing robust and efficient web applications. This tutorial aims to provide a comprehensive understanding of these objects' functionalities and demonstrate how to implement them effectively in Express.js applications.
Understanding the Request Object
The request object, often abbreviated as req
, represents the HTTP request and includes various properties that provide details about the incoming request.
Key Properties and Methods of the Request Object
req.query
: Contains the URL query parameters.req.params
: Contains route parameters.req.body
: Contains data sent in the request body (requires body-parser middleware).req.method
: The HTTP method used (GET, POST, etc.).req.url
: The URL of the request.req.headers
: Contains the headers of the request.
Accessing Query Parameters
Query parameters are the key-value pairs in the URL after the ?
mark. You can access them using the req.query
object. Here's an example:
Example:
// Require the Express module
const express = require('express');
// Create an Express application
const app = express();
// Define a route that accesses and returns query parameters
app.get('/search', (req, res) => {
// Access the query parameter 'q' from the request
const queryParam = req.query.q;
// Check if the query parameter exists
if (queryParam) {
// Respond with the query parameter value
res.send(`Search query: ${queryParam}`);
} else {
// Respond with an error message if 'q' is not provided
res.status(400).send('Query parameter "q" is required');
}
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Accessing Route Parameters
Route parameters are named segments of the URL, specified by colon prefixes, that capture values at specific positions within the URL. Here's how you can access route parameters in an Express.js application:
Example:
// Require the Express module
const express = require('express');
// Create an Express application
const app = express();
// Define a route with a parameter for user ID
app.get('/user/:id', (req, res) => {
// Access the route parameter 'id' from the request
const userId = req.params.id;
// Respond with the user ID
res.send(`User ID: ${userId}`);
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Accessing Request Body
To access the request body in an Express.js application, you typically need to use middleware that can parse the body of incoming requests. Here's an example using the built-in express.json()
middleware to parse JSON-formatted request bodies:
Example:
// Require the Express module
const express = require('express');
// Create an Express application
const app = express();
// Use middleware to parse JSON bodies
app.use(express.json());
// Define a route to access and respond with data from the request body
app.post('/profile', (req, res) => {
// Access the body from the request
const requestBody = req.body;
// Respond with the data from the request body
res.send(`Received the following data: ${JSON.stringify(requestBody)}`);
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Accessing HTTP Method
Here's an example demonstrating how to access the HTTP method used in a request:
Example:
// Require the Express module
const express = require('express');
// Create an Express application
const app = express();
// Define a route that accesses and returns the HTTP method
app.all('/method', (req, res) => {
// Access the HTTP method from the request
const method = req.method;
// Respond with the HTTP method used
res.send(`HTTP Method used in the request: ${method}`);
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Accessing Request URL
Here's an example demonstrating how to access and respond with the URL of an incoming request in an Express.js application:
Example:
// Require the Express module
const express = require('express');
// Create an Express application
const app = express();
// Define a route that accesses and returns the request URL
app.get('/request-url', (req, res) => {
// Access the URL from the request
const requestUrl = req.url;
// Respond with the request URL
res.send(`The requested URL is: ${requestUrl}`);
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Accessing Request Headers
Here's an example of how to access request headers in an Express.js application. This code demonstrates setting up a route that reads and responds with the headers sent by the client:
Example:
// Require the Express module
const express = require('express');
// Create an Express application
const app = express();
// Define a route to access and return request headers
app.get('/headers', (req, res) => {
// Access the headers from the request
const headers = req.headers;
// Respond with the headers in JSON format
res.json(headers);
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Understanding the Response Object
The response object, commonly abbreviated as res
, represents the HTTP response that an Express app sends when it gets an HTTP request. It includes methods for setting the response status, headers, and body.
Key Properties and Methods of the Response Object
res.send()
: Sends a response of various types.res.json()
: Sends a JSON response.res.status()
: Sets the HTTP status for the response.res.redirect()
: Redirects to a specified URL.res.render()
: Renders a view template.res.sendFile()
: Sends a file as an octet stream.
Sending Response
Here's an example showing how to send various types of responses using Express.js. This example covers sending plain text, HTML content, and JSON, demonstrating the versatility of the res.send()
method:
Example:
// Require the Express module
const express = require('express');
// Create an Express application
const app = express();
// Define a route to send a plain text response
app.get('/text', (req, res) => {
// Send plain text response
res.send('Hello, this is a plain text response!');
});
// Define a route to send HTML content
app.get('/html', (req, res) => {
// Send HTML response
res.send('<h1>Hello World</h1><p>This is an HTML response.</p>');
// Optionally, log the response to the console
console.log('Sent an HTML response');
});
// Define a route to send a JSON response
app.get('/json', (req, res) => {
// Send JSON response
res.send({ message: 'This is a JSON response', status: 'Success' });
// Optionally, log the response to the console
console.log('Sent a JSON response');
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Sending a JSON Response
Here's an example of how to send a JSON response using Express.js. This code demonstrates setting up a route that responds with JSON data when accessed:
Example:
// Require the Express module
const express = require('express');
// Create an Express application
const app = express();
// Define a route that sends a JSON response
app.get('/json', (req, res) => {
// Define the JSON data to send
const data = {
name: 'Alex',
age: 30,
occupation: 'Engineer'
};
// Send the JSON response
res.json(data);
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Setting the Response Status
Here's an example demonstrating how to set the HTTP response status in an Express.js application:
Example:
// Require the Express module
const express = require('express');
// Create an Express application
const app = express();
// Define a route to handle requests and set a custom response status
app.get('/status', (req, res) => {
// Set the HTTP status code to 404
res.status(404).send('Resource not found');
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Redirecting to a New URL
Here's an example of how to implement redirection to a new URL in an Express.js application:
Example:
// Require the Express module
const express = require('express');
// Create an Express application
const app = express();
// Define a route that redirects to a new URL
app.get('/redirect', (req, res) => {
// Specify the URL to which the response should redirect
res.redirect('https://www.example.com');
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Rendering Views with Template Engines
Here's an example of how you can use the res.render()
method in Express.js to render views using a template engine:
Example:
// Require Express and path modules
const express = require('express');
const path = require('path');
// Create an Express application
const app = express();
// Set the view engine to ejs and specify the views directory
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Define a route to render an ejs view
app.get('/render', (req, res) => {
// Render the 'index' view with a title variable
res.render('index', { title: 'Express Render Example' });
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Sending a File Response
Here's an example demonstrating how to send a file response using Express.js. This example serves a specific file from a given path when a particular route is accessed:
Example:
// Require Express and path modules
const express = require('express');
const path = require('path');
// Create an Express application
const app = express();
// Define a route to send a file
app.get('/file', (req, res) => {
// Set the path to the file
const filePath = path.join(__dirname, 'example.pdf');
// Send the file at the specified path
res.sendFile(filePath, function(err) {
if (err) {
console.log('Error sending file:', err);
res.status(500).send('Error sending file');
} else {
console.log('File sent successfully');
}
});
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Conclusion
In this tutorial, you learned about the crucial request and response objects in Express.js, which are essential for handling client-server communication. By understanding and utilizing these objects effectively, you can manage data retrieval, send appropriate responses, and handle errors efficiently. This knowledge enhances your ability to create robust and functional Express.js applications.