質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

TypeScript

TypeScriptは、マイクロソフトによって開発された フリーでオープンソースのプログラミング言語です。 TypeScriptは、JavaScriptの構文の拡張であるので、既存の JavaScriptのコードにわずかな修正を加えれば動作します。

Express

ExpressはNode.jsのWebアプリケーションフレームワークです。 マルチページを構築するための機能セットおよびハイブリッドのWebアプリケーションを提供します。

Q&A

解決済

2回答

193閲覧

Express.js(TypeScript)のプロジェクトでrouterがうまく動かなくて困っています

miu1

総合スコア5

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

TypeScript

TypeScriptは、マイクロソフトによって開発された フリーでオープンソースのプログラミング言語です。 TypeScriptは、JavaScriptの構文の拡張であるので、既存の JavaScriptのコードにわずかな修正を加えれば動作します。

Express

ExpressはNode.jsのWebアプリケーションフレームワークです。 マルチページを構築するための機能セットおよびハイブリッドのWebアプリケーションを提供します。

0グッド

0クリップ

投稿2024/03/12 13:21

編集2024/03/12 13:26

Express.js(TypeScript)のプロジェクトでrouterがうまく動かなくて困っています。

express-generatorで作成した、Express.jsプロジェクトをTypeScriptに変換して、
./src/index.tsを作成し、
ts-nodeで実行できるところまで確認しています。

この2つはjsonが返ってきますが、
http://localhost:3000
http://localhost:3000/api

./src/api/employeeApiController.tsを用意し、このControllerにアクセスさせようとして、
アドレスを入力してもアクセスできなくフリーズしています。
http://localhost:3000/api/employees

わかるかたいらっしゃればお願いします。

■./src/index.ts

TypeScript

1import express, { Request, Response, NextFunction } from "express"; 2import createError from "http-errors"; 3import path from "path"; 4import cookieParser from "cookie-parser"; 5import logger from "morgan"; 6 7const app = express(); 8 9app.use(logger("dev")); 10app.use(express.json()); 11app.use(express.urlencoded({ extended: false })); 12app.use(cookieParser()); 13 14// ルーターのマウント 15import { employeeApiController } from "./api/employeeApiController"; 16app.use("/api/employees", employeeApiController); 17 18// APIアクセス用のルートハンドラ 19app.get("/api", (req: Request, res: Response, next: NextFunction) => { 20 res.json({ message: "200 OK" }); 21}); 22 23// catch 404 and forward to error handler 24app.use(function (req: Request, res: Response, next: NextFunction) { 25 next(createError(404)); 26}); 27 28// error handler 29app.use(function (err: Error, req: Request, res: Response, next: NextFunction) { 30 // set locals, only providing error in development 31 res.locals.message = err.message; 32 res.locals.error = req.app.get("env") === "development" ? err : {}; 33 34 // render the error page 35 const httpStatusCode = (err as any).status || 500; 36 res.status(httpStatusCode).json({ message: httpStatusCode + " " + err.message }); 37}); 38 39// ポート指定 40const port = process.env.PORT || 3000; 41app.listen(port, () => { 42 console.log(`Server is running on port ${port}`); 43}); 44 45module.exports = app;

■./src/api/employeeApiController.ts

TypeScript

1import express, { Request, Response, NextFunction } from "express"; 2 3export const employeeApiController = () => { 4 const router = express.Router(); 5 6 // GET /api/employees 7 router.get( 8 "/", 9 (request: Request, response: Response, next: NextFunction) => { 10 async () => { 11 response.json({ message: "done" }); 12 }; 13 } 14 ); 15 16 return router; 17};

■ tsconfig.json

json

1{ 2 "compilerOptions": { 3 "target": "es6", 4 "module": "commonjs", 5 "outDir": "./dist", 6 "strict": true, 7 "esModuleInterop": true, 8 "sourceMap": true 9 }, 10 "include": ["./src/**/*.ts"], 11 "exclude": ["node_modules"] 12}

■ package.json

json

1{ 2 "name": "backend", 3 "version": "0.0.0", 4 "private": true, 5 "scripts": { 6 "dev": "ts-node ./src/index.ts", 7 "start": "node ./bin/www" 8 }, 9 "dependencies": { 10 "cookie-parser": "~1.4.4", 11 "debug": "~2.6.9", 12 "express": "~4.16.1", 13 "morgan": "~1.9.1" 14 }, 15 "devDependencies": { 16 "@types/cookie-parser": "^1.4.7", 17 "@types/debug": "^4.1.12", 18 "@types/express": "^4.17.21", 19 "@types/http-errors": "^2.0.4", 20 "@types/morgan": "^1.9.9", 21 "@types/node": "^16.11.10", 22 "ts-node": "10.9.1", 23 "ts-node-dev": "^2.0.0", 24 "typescript": "4.5.2" 25 } 26} 27

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

js

1app.use("/api/employees", employeeApiController);

employeeApiController を呼ぶ必要があるのではないでしょうか。

js

1app.use("/api/employees", employeeApiController());

投稿2024/03/12 22:39

int32_t

総合スコア20884

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

miu1

2024/03/12 23:18

ご回答ありがとうございます。 確かにexportするものを、関数を入れているので()がつくのが正しいのかなと思いますが、 アクセスできず、コンソールにもエラーが表示されない状態です。
miu1

2024/03/13 11:23 編集

default exportにすると、 -- import express, { Request, Response, NextFunction } from "express"; const router = express.Router(); // GET /api/employees router.get("/", (request: Request, response: Response, next: NextFunction) => { response.json({ message: "done" }); }); export default router; -- アクセスこそできましたが、今の設定だとnamed exportができないようです。
miu1

2024/03/13 11:48 編集

index.tsに employeeApiController()のように括弧が必要なのはご指摘通りで、asyncが原因でした。 apiにasyncは付けるのは難しいのでしょうか。 import express, { Request, Response, NextFunction } from "express"; export const employeeApiController = () => { const router = express.Router(); // GET /api/employees router.get( "/", (request: Request, response: Response, next: NextFunction) => { // async () => { response.json({ message: "done" }); // }; } ); return router; }; ネットで検索したところ、catchにnext()を入れる必要があるかもしれません。
guest

0

自己解決

自己解決できました。
ご指摘があったindex.tsにemployeeApiController() のように括弧をつけることと、
employeeApiController.tsのasyncの位置を修正、例外処理を追加して、catchでnextを実行するようにしました。

TypeScript

1import express, { Request, Response, NextFunction } from "express"; 2// import { employeeService } from "employeeService"; 3 4export const employeeApiController = () => { 5 const router = express.Router(); 6 7 // GET /api/employees 8 router.get( 9 "/", 10 async (request: Request, response: Response, next: NextFunction) => { 11 try { 12 response.json({ message: "done" }); 13 // 実際はserviceなどを呼ぶ、コードはイメージ。 14 // const employees = await employeeService.find(); 15 // response.json(employees); 16 } catch (exception: any) { 17 next(exception); 18 } 19 } 20 ); 21 22 return router; 23};

投稿2024/03/13 11:57

編集2024/03/13 13:30
miu1

総合スコア5

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問