Mark As Completed Discussion

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:

JAVASCRIPT
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.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment