0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ExpressのRouterについて

Posted at

Express.jsはNode.jsのための軽量なWebアプリケーションフレームワークの一つです。この記事では、その中でも「Router」の機能に焦点を当て、初心者にもわかりやすく説明します。

1. Routerの基本

👉 ポイント: Routerは、Expressアプリのルーティングをモジュール化するためのミドルウェアです。

Expressアプリケーションでは、特定のURLへのリクエストにどのようなレスポンスを返すかを決める「ルーティング」を設定します。Routerを使用すると、これらのルーティングをきれいにモジュール化して、コードの構造を整理することができます。

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

router.get('/hello', (req, res) => {
  res.send('Hello Router!');
});

app.use(router);
app.listen(3000);

2. Routerの利点

👉 ポイント: Routerを使うことで、アプリケーションの構造をシンプルに保つことができます。

大規模なアプリケーションになると、ルーティングの数も増えてきます。Routerを活用することで、それぞれのルーティングを個別のファイルやモジュールに分割して管理することが可能になります。

3. ミドルウェアとしてのRouter

👉 ポイント: Routerはミドルウェアとしても機能します。

ExpressのRouterは、特定のパスでのみ動作するミドルウェア関数のシリーズを定義できます。これにより、特定のルートに対して前処理や後処理を行うことができます。

router.use((req, res, next) => {
  console.log('Router middleware');
  next();
});

router.get('/test', (req, res) => {
  res.send('Test Route');
});

4. ルートパラメータの利用

👉 ポイント: Routerを使うことで、動的なルートパラメータを簡単に取り扱うことができます。

ユーザーIDや商品IDなど、URLの一部が動的に変わる場合があります。Routerを使えば、これらの動的な部分をパラメータとして取得し、それを利用した処理を行うことができます。

router.get('/user/:id', (req, res) => {
  const userId = req.params.id;
  res.send(`User ID: ${userId}`);
});
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?