APIのエントリーポイントの定義
メニューを表示するにはスワイプしてください
index.js ファイルは、サーバーの設定、ミドルウェアの定義、ルートの設定、エラー処理を行う場所です。Express アプリケーションの中心的な役割を果たします。
必要なモジュールとファイルのインポート
index.js は、サーバーの設定、ミドルウェアの定義、ルートの設定、エラー処理を行う場所です。コードを段階的に分解して説明します。
const express = require("express"); // Import the `Express` framework
const app = express(); // Create an `Express` application instance
const router = require("./routes/postsRoutes"); // Import the `router` module for posts
const PORT = process.env.PORT || 3000; // Define the port for the server
JSONパース用ミドルウェア
app.use(express.json()); // Use the `express.json()` middleware for parsing JSON requests
express.json()ミドルウェアは、受信したJSONリクエストをパースし、データをreq.bodyで利用可能にする機能。POSTおよびPUTリクエストでJSONデータを扱う際に不可欠な要素。
ルート設定
ルーティングは、アプリケーションがクライアントリクエストにどのように応答するかを定義する仕組み。
app.use("/api", router); // Use the router for handling routes under the `"/api"` path
ルーティングは、アプリケーションがクライアントリクエストにどのように応答するかを定義するもの。このコード行では、routerで定義されたpostsRoutes.jsが/apiパス配下のルートを処理するよう指定。
エラーハンドリングミドルウェア
エラーハンドリングは、アプリケーションがエラーを適切に処理するために重要な要素。
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack); // Log the error to the console
res.status(500).json({ error: "Internal Server Error" }); // Send a 500 Internal Server Error response
});
- このミドルウェアは、リクエスト処理中に発生したエラーを捕捉する役割;
- それ以前のミドルウェアやルートハンドラで
next(err)が呼ばれた場合、このミドルウェアがエラーを捕捉; console.error(err.stack)でエラーをコンソールに出力;- サーバー側で問題が発生したことを示す500 Internal Server Errorレスポンスをクライアントに送信。
サーバーの起動
アプリケーションのセットアップを完了するために、指定したポートでExpressサーバーを起動します。
// Start the Express server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`); // Log a message indicating the server is running
});
- この行でExpressサーバーが起動し、指定したポート(
PORT)でリッスンします。 - サーバーが起動すると、稼働中のポート番号をコンソールにメッセージとして出力します。
index.jsファイルの全コード
// Import required modules and files
const express = require("express"); // Import the `Express` framework
const app = express(); // Create an `Express` application instance
const router = require("./routes/postsRoutes"); // Import the `router` module for posts
const PORT = process.env.PORT || 3000; // Define the port for the server
app.use(express.json()); // Use the `express.json()` middleware for parsing JSON requests
app.use("/api", router); // Use the `router` for handling routes under the `"/api"` path
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack); // Log the error to the console
res.status(500).json({ error: "Internal Server Error" }); // Send a `500 Internal Server Error` response
});
// Start the Express server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`); // Log a message indicating the server is running
});
すべて明確でしたか?
フィードバックありがとうございます!
セクション 4. 章 4
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 4. 章 4