Routing with Express.js
Express.js is a popular web application framework for Node.js. It provides a robust set of features for building web applications and APIs. One of the key features of Express.js is its routing capabilities, which allow you to define how your application responds to requests.
Routing in Express.js is based on the use of HTTP methods such as GET, POST, PUT, and DELETE, as well as the URL pattern to which a specific route should respond. This makes it possible to define different routes for different parts of your application, and handle requests in a way that makes sense for your specific use case.
Let’s take a look at how routing works in Express.js with some examples:
“`javascript
const express = require(‘express’);
const app = express();
// Define a route that responds to GET requests
app.get(‘/’, (req, res) => {
res.send(‘Hello, World!’);
});
// Define a route that responds to POST requests
app.post(‘/users’, (req, res) => {
// Create a new user in the database
res.send(‘User created successfully’);
});
// Define a route that responds to PUT requests
app.put(‘/users/:id’, (req, res) => {
// Update the user with the specified ID
res.send(‘User updated successfully’);
});
// Define a route that responds to DELETE requests
app.delete(‘/users/:id’, (req, res) => {
// Delete the user with the specified ID
res.send(‘User deleted successfully’);
});
// Start the server
app.listen(3000, () => {
console.log(‘Server is running on port 3000’);
});
“`
In this example, we’ve defined four different routes using Express.js. The first route responds to a GET request to the root URL of our application and simply sends a “Hello, World!” message back to the client. The second route responds to a POST request to the “/users” URL, which is typically used to create a new user. The third and fourth routes respond to PUT and DELETE requests to the “/users/:id” URL, which is used to update and delete a specific user, respectively.
One of the great things about Express.js is its flexibility when it comes to defining routes. You can use dynamic route parameters, middleware, and route handlers to create a powerful and flexible routing system for your web applications and APIs.
Overall, routing with Express.js is a powerful feature that makes it easy to handle different types of requests and define how your application responds to them. Whether you’re building a simple web application or a complex API, Express.js provides the tools you need to define and manage your routes with ease.