Routing in Express.js
1. Introduction
Routing in Express.js is a way to define the endpoints (URLs) of your web application and associate them with specific request handlers. This enables you to build RESTful APIs and web applications efficiently.
2. Routing Basics
In Express.js, the routing mechanism allows you to handle different HTTP requests to different endpoints. You can define routes using the app.get()
, app.post()
, app.put()
, and app.delete()
methods.
Example: Basic Routing
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to Express.js!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
3. HTTP Methods
Express.js supports various HTTP methods which correspond to the CRUD operations:
- GET - Retrieve data
- POST - Create new data
- PUT - Update existing data
- DELETE - Remove data
4. Route Parameters
Route parameters allow you to capture values from the URL. You can define a route with a parameter by prefixing it with a colon.
Example: Route Parameters
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
5. Middleware Functions
Middleware functions are functions that have access to the request object, response object, and the next middleware function. Middleware can modify the request and response objects, end the request-response cycle, or call the next middleware function.
Example: Use of Middleware
const logger = (req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
};
app.use(logger);
6. Best Practices
When working with routing in Express.js, consider the following best practices:
- Organize routes in separate files for better maintainability.
- Use descriptive route names.
- Implement error handling middleware.
- Validate input data to ensure security.
7. FAQs
What is the difference between app.get() and app.post()?
app.get() is used to define a route that handles GET requests, while app.post() is used for POST requests, typically for creating new resources.
Can I define multiple routes for the same path?
Yes, you can define multiple handlers for the same route with different HTTP methods or with the same method by adding different middleware.
What are route chains?
Route chains allow you to group multiple middleware functions that will be executed sequentially for a specific route.