This content originally appeared on DEV Community and was authored by bihiui lolik
Node.jsでAPIサーバーを作成する
はじめに
Node.jsとExpressを使用して、シンプルなREST APIサーバーを作成する方法を紹介します。
必要な準備
Node.jsがインストールされていることを確認してください。次に、express
をインストールします。
npm init -y
npm install express
APIサーバーの作成
以下のコードで、基本的なGETとPOSTリクエストを処理するAPIを作成します。
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
const tasks = [];
// タスクを取得
app.get('/tasks', (req, res) => {
res.json(tasks);
});
// タスクを追加
app.post('/tasks', (req, res) => {
const task = req.body;
tasks.push(task);
res.status(201).json(task);
});
app.listen(PORT, () => {
console.log(`APIサーバーが http://localhost:${PORT} で起動しました`);
});
コードの説明
-
express
モジュールをインポート。 -
app.use(express.json())
でJSONリクエストの解析を有効化。 -
GET /tasks
でタスク一覧を取得。 -
POST /tasks
で新しいタスクを追加。 -
app.listen(PORT, () => {...})
でポート3000でAPIサーバーを起動。
APIの実行
以下のコマンドでサーバーを起動できます。
node server.js
ターミナルやPostmanで以下のリクエストを送信して動作を確認できます。
- タスク一覧取得:
GET http://localhost:3000/tasks
- タスク追加:
POST http://localhost:3000/tasks
(JSONデータ付き)
まとめ
本記事では、Node.jsとExpressを使用して簡単なREST APIを作成しました。次回は、MongoDBを使用してデータを永続化する方法を紹介します。
This content originally appeared on DEV Community and was authored by bihiui lolik

bihiui lolik | Sciencx (2025-03-01T20:26:10+00:00) https://rb.gy/3jou1h. Retrieved from https://www.scien.cx/2025/03/01/https-rb-gy-3jou1h/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.