LoginSignup
0
1

"Node.jsとExpressでのルートハンドラーのモジュール化

Last updated at Posted at 2023-09-28

はじめに

Node.jsとExpressを利用したWebアプリケーション開発において、コードの構造化は非常に重要です。この記事では、ルートハンドラーをモジュール化する一例を紹介します。

ルートハンドラーの設定

まず、以下のコードスニペットは、Expressのルーターを設定し、/userエンドポイントに対するGETリクエストがあった際に、home関数が呼び出されるようにしています。

const { home } = require('../controllers/user');
const express = require('express');
const router = express.Router();

router.get('/user', home);

module.exports = router;

home関数の定義

次に、ルートハンドラーで実行したいhome関数を別のファイルで定義し、exportすればokです!

exports.home = (req, res) => {
  res.json({ user: 'user data' });
};

まとめ

このように、コントローラーを別のファイルで定義し、ルーターでインポートすることによって、コードの再利用性が向上し、メンテナンスも容易になります。これにより、開発者はより効率的かつ効果的にコードの構造化を進めることができます。

0
1
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
1