1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Reactとバックエンドで作る!実践Web開発入門 | 第3章: バックエンドでAPIを作成

Posted at

はじめに

第2章ではReactでUIを構築しました。今回は、バックエンド(Node.jsとExpress)でAPIを作り、Reactがデータを取得できるようにします。商品リストをサーバーから提供する例を通じて、RESTful APIの基本を学びます。

目標

  • RESTful APIの基本を理解する
  • Expressで簡単なAPIを作成する
  • フロントエンドとバックエンドの通信を準備する

RESTful APIとは

RESTful APIは、HTTPメソッド(GET, POSTなど)を使ってデータをやり取りする仕組みです。今回は以下のエンドポイントを作ります:

  • GET /products: 商品リストを取得。

バックエンドの準備

backendフォルダに移動し、必要な設定を行います。まだExpressをインストールしていない場合は以下を実行:

npm install express

APIの実装

backend/index.jsを以下のように更新します:

const express = require('express');
const app = express();
const port = 5000;

// サンプルデータ
const products = [
  { id: 1, name: 'りんご', price: 100 },
  { id: 2, name: 'バナナ', price: 150 },
];

// JSON形式でデータを返す
app.use(express.json());

// GET /products エンドポイント
app.get('/products', (req, res) => {
  res.json(products);
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
  • productsは仮のデータベースとして使用。
  • res.json()でJSON形式でデータを返します。

サーバーを起動:

node index.js

http://localhost:5000/productsにアクセスすると、商品リストがJSONで表示されます:

[
  {"id": 1, "name": "りんご", "price": 100},
  {"id": 2, "name": "バナナ", "price": 150}
]

CORSの設定

React(ポート3000)からバックエンド(ポート5000)にアクセスするには、CORSを許可する必要があります。以下を実行してcorsパッケージを追加:

npm install cors

index.jsを更新:

const express = require('express');
const cors = require('cors');
const app = express();
const port = 5000;

const products = [
  { id: 1, name: 'りんご', price: 100 },
  { id: 2, name: 'バナナ', price: 150 },
];

app.use(express.json());
app.use(cors()); // CORSを有効化

app.get('/products', (req, res) => {
  res.json(products);
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

これで、異なるポート間での通信が可能になります。

APIのテスト

Postmanやブラウザでhttp://localhost:5000/productsを試してください。JSONデータが正しく返されるか確認します。また、以下のようなcurlコマンドでもテストできます:

curl http://localhost:5000/products

次回予告

第4章では、ReactからこのAPIを呼び出し、商品リストを動的に表示する方法を学びます。お楽しみに!


この記事が役に立ったら、ぜひ「いいね」や「ストック」をお願いします!質問や感想はコメント欄で気軽にどうぞ。次回も一緒に学びましょう!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?