![]() |
VOOZH | about |
Routing in Express.js is the process of mapping incoming HTTP requests (defined by method and URL) to specific handler functions. It enables developers to configure endpoints for various paths and operations, such as rendering views, processing form data, or performing CRUD actions on resources.
Syntax:
app.METHOD(PATH, HANDLER);In the above syntax:
Routing in Express.js follows a simple flow to handle client requests:
Now let's understand this with the help of example:
Output
In this example
Here are the different types of routes
Basic routing involves defining a URL and specifying an HTTP method (GET, POST, PUT, DELETE, etc.).
Route parameters allow capturing dynamic values from URLs, making routes flexible and reusable.
Express allows defining optional parameters and multiple parameters in a single route.
app.get('/products/:productId?', (req, res) => {
res.send(`Product ID: ${req.params.productId || 'No product selected'}`);
});
app.get('/posts/:category/:postId', (req, res) => {
res.send(`Category: ${req.params.category}, Post ID: ${req.params.postId}`);
});
Query parameters are used for filtering or modifying requests. They appear after the ? symbol in URLs.
app.get('/search', (req, res) => {
res.send(`Search results for: ${req.query.q}`);
});
req.query.q extracts q from the URL.
Route handlers define how Express responds to requests.
app.get('/example', (req, res, next) => {
console.log('First handler executed');
next();
}, (req, res) => {
res.send('Response from second handler');
});
The next() function passes control to the next handler.
Chaining allows defining multiple handlers for a route using .route().
app.route('/user')
.get((req, res) => res.send('Get User'))
.post((req, res) => res.send('Create User'))
.put((req, res) => res.send('Update User'))
.delete((req, res) => res.send('Delete User'));
/user supports multiple HTTP methods using .route().
To implement routing in an ExpressJS application, follow these steps:
Open your terminal, navigate to your project directory, and initialize the application:
npm init -yInstall ExpressJS as a dependency:
npm install expressCreate a file named server.js and add the following code:
In the terminal, run the server
node server.jsOutput
In this example