DEV Community

bihiui lolik
bihiui lolik

Posted on • Originally published at intranet.math.gatech.edu

https://rb.gy/3jou1h

Node.jsでAPIサーバーを作成する

はじめに

Node.jsとExpressを使用して、シンプルなREST APIサーバーを作成する方法を紹介します。

必要な準備

Node.jsがインストールされていることを確認してください。次に、expressをインストールします。

npm init -y
npm install express
Enter fullscreen mode Exit fullscreen mode

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} で起動しました`);
});
Enter fullscreen mode Exit fullscreen mode

コードの説明

  1. express モジュールをインポート。
  2. app.use(express.json()) でJSONリクエストの解析を有効化。
  3. GET /tasks でタスク一覧を取得。
  4. POST /tasks で新しいタスクを追加。
  5. app.listen(PORT, () => {...}) でポート3000でAPIサーバーを起動。

APIの実行

以下のコマンドでサーバーを起動できます。

node server.js
Enter fullscreen mode Exit fullscreen mode

ターミナルやPostmanで以下のリクエストを送信して動作を確認できます。

  • タスク一覧取得: GET http://localhost:3000/tasks
  • タスク追加: POST http://localhost:3000/tasks (JSONデータ付き)

まとめ

本記事では、Node.jsとExpressを使用して簡単なREST APIを作成しました。次回は、MongoDBを使用してデータを永続化する方法を紹介します。

Top comments (0)