Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Organizing Routes with Router | Routing in Express.js
Express.js Essentials for Backend Development

Organizing Routes with Router

メニューを表示するにはスワイプしてください

When your Express.js application grows, managing all routes in a single file quickly becomes unwieldy. To keep your codebase clean and maintainable, you can use the Express Router to modularize your routes. The Router allows you to split related routes into separate modules, each handling a specific part of your application. This approach not only improves readability but also makes it easier to reuse and test route logic.

Suppose you want to organize all user-related routes in a dedicated file. You would create a new file, such as users.js, to define these routes using an Express Router instance, and then import this router into your main application file (app.js). Here is how you can structure your code:

users.js (router module):

const express = require('express');
const router = express.Router();

// GET /users/
router.get('/', (req, res) => {
  res.send('List of users');
});

// GET /users/:id
router.get('/:id', (req, res) => {
  res.send(`User with ID: ${req.params.id}`);
});

module.exports = router;

app.js (main application file):

const express = require('express');
const app = express();
const usersRouter = require('./users');

app.use('/users', usersRouter);

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

In this setup, users.js exports a router instance that defines all user-related routes. The main application file imports this router and mounts it at the /users path with app.use('/users', usersRouter). As a result, requests to /users or /users/:id are handled by the router defined in users.js. This modular approach lets you keep your route logic organized and enables you to scale your application more easily.

The Express Router is a mini Express application that you can attach to your main app. It provides a way to organize routes into separate modules based on features or resources, such as users, products, or orders. The main benefits of modular routing are:

  • Improved code organization by grouping related routes together;
  • Easier maintenance and scalability as your application grows;
  • Simplified testing and reuse of route logic;
  • Clear separation of concerns between different parts of your application.

You can also use router-level middleware with Express Router. This means you can add middleware functions that apply only to routes within a specific router module, such as authentication or logging for user routes. To use router-level middleware, simply add it to your router instance before your route handlers:

router.use((req, res, next) => {
  console.log('Request made to user routes');
  next();
});

By using Express Router and router-level middleware, you create a more structured and maintainable codebase, especially as your application becomes more complex.

question mark

Which of the following best describes the main purpose and benefits of using Express Router to organize your routes?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 2.  3

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 2.  3
some-alt