Routing in Express
When building an Express.js application, one of the key components is configuring routes. Routing involves defining the logic for handling requests to different endpoints or URLs. Express provides a flexible routing system that allows you to create modular and organized routes.
Configuring Routes with Express Router
To configure routes in an Express.js application, you can use the express.Router()
method to create a new router object. This allows you to define routes specific to particular URLs or endpoints.
Here's an example of configuring routes using Express Router:
1// 1. Create a new router object
2const router = express.Router();
3
4// 2. Define routes
5router.get('/', (req, res) => {
6 // Handle GET request to '/'
7 res.send('Hello, World!');
8});
9
10router.post('/users', (req, res) => {
11 // Handle POST request to '/users'
12 const user = req.body;
13 // Save user data to database
14 db.save(user);
15 res.status(201).json({
16 message: 'User created successfully',
17 user,
18 });
19});
20
21// 3. Mount the router
22app.use('/api', router);
In this example, a new router object is created using express.Router()
. Two routes are defined: a GET route for the root URL ('/'
) and a POST route for the /users
URL. The router is then mounted on the '/api'
path using app.use()
. This means that any requests to '/api'
or its sub-paths will be handled by the router.
Routing in Express allows you to modularize your application and handle specific endpoints or URLs with separate logic. This makes it easier to organize and maintain your code, especially as your application grows in size and complexity.
xxxxxxxxxx
// Routing in Express allows you to modularize your application and handle specific endpoints or URLs with separate logic. This makes it easier to organize and maintain your code, especially as your application grows in size and complexity.
// Configuring routes in Express
// To configure routes in an Express.js application, you can use the `express.Router()` method to create a new router object. This allows you to define routes specific to particular URLs or endpoints.
// Here's an example of configuring routes using Express Router:
// 1. Create a new router object
const router = express.Router();
// 2. Define routes
router.get('/', (req, res) => {
// Handle GET request to '/'
res.send('Hello, World!');
});
router.post('/users', (req, res) => {
// Handle POST request to '/users'
const user = req.body;
// Save user data to database
db.save(user);
res.status(201).json({
message: 'User created successfully',
user,
});
});
// 3. Mount the router
app.use('/api', router);