Introduction
Express.js is one of the most popular and lightweight frameworks for building web applications and APIs in Node.js. It simplifies handling HTTP requests, providing an easy-to-use set of methods and middleware for creating routes, handling requests, and sending responses. One of the key features of Express is its powerful routing system, which enables developers to define various endpoints and handle requests using a variety of HTTP methods such as GET, POST, PUT, DELETE, and more.
In this post, we will delve into basic routing in Express.js. You will learn how to define routes using methods like app.get()
, app.post()
, and others. We will explore how to handle requests at different endpoints, how to extract parameters and query strings, and how to send appropriate responses to clients.
1. What is Routing in Express.js?
Routing is the process of defining endpoints that correspond to specific HTTP methods and URL paths. A route is essentially a function that is executed when a certain URL pattern is matched, and it specifies the logic that should be executed for that request.
In Express.js, routing is handled using methods such as:
app.get(path, callback)
: Handles HTTP GET requests.app.post(path, callback)
: Handles HTTP POST requests.app.put(path, callback)
: Handles HTTP PUT requests.app.delete(path, callback)
: Handles HTTP DELETE requests.
These methods define a route and bind it to a specific URL and HTTP method. When a request matches a defined route, the callback function is executed, and the server sends the corresponding response.
2. Setting Up a Basic Express Application
Before diving into routing, let’s quickly set up a basic Express application. First, you need to install Express.
2.1. Installing Express
If you haven’t installed Express yet, you can do so by running the following command:
npm install express
2.2. Creating a Basic Express Server
Once Express is installed, create a file (e.g., app.js
) and set up a simple server.
const express = require('express');
const app = express();
// Define a simple route
app.get('/', (req, res) => {
res.send('Hello, World!');
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
2.3. Running the Server
Run the application using:
node app.js
This will start the server at http://localhost:3000
. When you navigate to this URL in your browser, you should see the text “Hello, World!”.
3. Defining Routes with app.get()
The app.get()
method in Express is used to handle GET requests. GET requests are typically used to retrieve data from the server. For example, a GET request could fetch a webpage or retrieve data from an API.
3.1. Basic GET Route
Here’s an example of a simple route that responds to GET requests:
app.get('/greeting', (req, res) => {
res.send('Welcome to Express!');
});
When you navigate to http://localhost:3000/greeting
, you will receive the response “Welcome to Express!”.
3.2. Dynamic Routes with URL Parameters
You can also create dynamic routes that accept URL parameters. URL parameters are defined using a colon (:
) followed by the name of the parameter.
Example:
app.get('/user/:id', (req, res) => {
const userId = req.params.id; // Access the 'id' parameter from the URL
res.send(User ID is ${userId}
);
});
Now, if you visit http://localhost:3000/user/123
, the response will be:
User ID is 123
Express automatically parses the URL parameters and makes them accessible via req.params
.
4. Handling POST Requests with app.post()
The app.post()
method is used to handle POST requests. POST requests are typically used when the client wants to send data to the server, such as when submitting a form or sending JSON data via an API.
4.1. Basic POST Route
Here’s a simple example of a POST route:
app.post('/submit', (req, res) => {
res.send('Data submitted successfully!');
});
When you make a POST request to http://localhost:3000/submit
(using a tool like Postman or via a form submission), you will receive the response “Data submitted successfully!”.
4.2. Parsing Request Body with Express Middleware
For POST requests, data is often sent in the request body. To work with this data, Express provides middleware to parse the body of the request. The express.json()
middleware parses incoming JSON payloads, while express.urlencoded()
parses URL-encoded data (such as form submissions).
To enable body parsing, add the following middleware to your Express app:
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
Now, let’s handle a POST request that sends JSON data.
app.post('/jsondata', (req, res) => {
const userData = req.body; // The incoming JSON data
res.json({
message: 'Data received',
receivedData: userData
});
});
To test this route, you can send a POST request with JSON data (e.g., using Postman or cURL). Here’s what the request might look like:
Request body:
{
"name": "John Doe",
"age": 30
}
Response:
{
"message": "Data received",
"receivedData": {
"name": "John Doe",
"age": 30
}
}
This demonstrates how to handle JSON data in POST requests.
5. Handling PUT and DELETE Requests
In addition to GET and POST, Express also supports other HTTP methods such as PUT and DELETE. These are commonly used for updating and deleting resources, respectively.
5.1. Handling PUT Requests with app.put()
PUT requests are used to update existing resources on the server. Here’s an example of how to handle a PUT request:
app.put('/updateUser/:id', (req, res) => {
const userId = req.params.id;
const updatedData = req.body;
res.json({
message: User with ID ${userId} has been updated
,
updatedData: updatedData
});
});
In this case, a PUT request to /updateUser/:id
can be used to update a specific user, passing the new data in the request body.
5.2. Handling DELETE Requests with app.delete()
DELETE requests are used to remove resources from the server. Here’s an example of how to handle a DELETE request:
app.delete('/deleteUser/:id', (req, res) => {
const userId = req.params.id;
res.json({
message: User with ID ${userId} has been deleted
});
});
A DELETE request to /deleteUser/:id
will delete the user with the provided ID.
6. Using Query Parameters in Routes
In addition to URL parameters, Express also allows you to work with query parameters. Query parameters are typically used to send optional data in the URL after the ?
symbol.
For example, a query parameter might look like this: /search?term=nodejs
.
6.1. Accessing Query Parameters
You can access query parameters via req.query
. Here’s an example:
app.get('/search', (req, res) => {
const searchTerm = req.query.term; // Access query parameter 'term'
res.send(Searching for: ${searchTerm}
);
});
If you navigate to http://localhost:3000/search?term=nodejs
, the response will be:
Searching for: nodejs
This is useful for handling search queries or any other optional data passed in the URL.
7. Responding with JSON
Express provides several methods to send responses to the client. For JSON responses, use the res.json()
method, which automatically sets the correct Content-Type header (application/json
) and converts an object or array to a JSON string.
7.1. Using res.json()
app.get('/user', (req, res) => {
const user = {
name: 'Alice',
email: '[email protected]'
};
res.json(user); // Sends a JSON response
});
The response will be:
{
"name": "Alice",
"email": "[email protected]"
}
8. Handling Errors in Routing
When building applications, it’s essential to handle errors gracefully. Express allows you to define custom error-handling routes that catch errors for specific routes or the entire application.
Here’s an example of how to handle errors for an invalid route:
app.use((req, res) => {
res.status(404).json({ message: 'Route not found' });
});
Leave a Reply