1. Routing and URL Parameters in Express
Routing is one of the core features of the Express.js framework. It enables the server to handle requests to different URLs and execute corresponding responses based on the request type (GET, POST, etc.). Express routing also supports dynamic routing through URL parameters, making it easy to build dynamic, interactive web applications.
2. Understanding Routing in Express
In Express, routing refers to how an application’s endpoints (URIs) respond to client requests. Each route can define multiple HTTP methods like GET, POST, PUT, DELETE, etc. Here's the basic structure of routing in Express:
app.METHOD(PATH, HANDLER)
3. Setting Up Basic Routes
Let’s set up some basic routes using Express:
const express = require('express');
const app = express();
const PORT = 3000;
// GET route for home page
app.get('/', (req, res) => {
res.send('Welcome to the Home Page!');
});
// GET route for About page
app.get('/about', (req, res) => {
res.send('Welcome to the About Page!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
4. Using URL Parameters
URL parameters allow routes to capture values embedded in the URL. They are defined using the colon (:) syntax in the route path.
Example:
// Route with URL parameter
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID is: ${userId}`);
});
5. Multiple URL Parameters
You can define multiple parameters in a route as needed.
Example:
app.get('/user/:id/:name', (req, res) => {
const { id, name } = req.params;
res.send(`User ID: ${id}, User Name: ${name}`);
});
6. Handling Query Strings
Express can also handle query strings, which are key-value pairs appended to the URL using the ? symbol.
Example:
app.get('/search', (req, res) => {
const { keyword, page } = req.query;
res.send(`Search results for: ${keyword}, Page: ${page}`);
});
7. Chaining Route Handlers
Express allows chaining multiple middleware functions to handle a single route.
Example:
app.get('/chained',
(req, res, next) => {
console.log('First middleware');
next();
},
(req, res) => {
res.send('Response from second middleware');
}
);
8. Error Handling for Routes
To handle invalid routes or errors, use a wildcard route (*) or an error-handling middleware.
Example:
// Handling undefined routes
app.get('*', (req, res) => {
res.status(404).send('Page not found');
});