MeWrite Docs

Express: Router not found - Cannot GET /path

Expressでルーティングが見つからない404エラーの原因と解決策

概要

Expressアプリケーションで定義したはずのルートにアクセスできない404エラーです。

エラーメッセージ

``` Cannot GET /api/users ```

原因

  1. ルーターのマウント忘れ: app.use() でルーターを登録していない
  2. パスの不一致: 定義したパスとリクエストパスが異なる
  3. ルーターの順序問題: catchall ルートが先に定義
  4. HTTPメソッドの不一致: GET vs POST 等

解決策

1. ルーターを正しくマウント

```javascript // routes/users.js const express = require(’express’); const router = express.Router();

router.get(’/’, (req, res) => { res.json({ users: [] }); });

module.exports = router;

// app.js const usersRouter = require(’./routes/users’);

// 正しくマウント app.use(’/api/users’, usersRouter); ```

2. ルートの順序を確認

```javascript // 悪い例: catchall が先 app.get(’*’, (req, res) => res.sendFile(‘index.html’)); app.use(’/api’, apiRouter); // 到達しない

// 良い例: 具体的なルートを先に app.use(’/api’, apiRouter); app.get(’*’, (req, res) => res.sendFile(‘index.html’)); ```

3. デバッグ用にルートを確認

```javascript // 登録されたルートを表示 function printRoutes(app) { app._router.stack.forEach((r) => { if (r.route) { console.log(r.route.path, Object.keys(r.route.methods)); } else if (r.name === ‘router’) { r.handle.stack.forEach((nested) => { if (nested.route) { console.log(nested.route.path, Object.keys(nested.route.methods)); } }); } }); } ```

4. 404ハンドラーを追加

```javascript // 全てのルートの後に配置 app.use((req, res, next) => { console.log(`404: ${req.method} ${req.path}`); res.status(404).json({ error: ‘Not Found’, path: req.path }); }); ```

よくある間違い

  • router.get() だけで app.use() を忘れる
  • パスの先頭スラッシュの有無
  • async/await でエラーが握りつぶされる

関連エラー

関連エラー

Node.js の他のエラー

最終更新: 2025-12-10