このチュートリアルでは、仮想化環境(Ubuntu)上で
- 初歩的なAPIの作成方法
- APIとフロントエンドの接続方法
を学びます。
環境
Ubuntu: 22.04.5 LTS
Node.js: v22.12.0 LTS
npm: 10.9.0
1. プロジェクトの設定
今回のタスクで使用する新しいディレクトリを作成しましょう。
1 |
mkdir api-demo |
api-demo
ディレクトリ下で、以下のコードをapi.js
という名前で保存しましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
'use strict'; const express = require('express'); const app = express(); // Enable CORS app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); // Show homepage app.get('/', (req, res, next) => { res.send('Hello World.'); }); // Show our results app.get('/fruits', (req, res, next) => { let list = { apples: 1, bananas: 5, oranges: 10 } res.json(list); }); // Catch 404 and forward to error handler app.use((req, res, next) => { res.status(404); res.type('txt').send('Error 404 - Not Found'); next(new Error('Not Found')); }); // Start the app app.listen(8081, () => { console.log('Listening on port 8081'); }); |
続いて、npmのためのコンフィグファイル作成します。
以下のコードをpackage.json
という名前で保存します。
1 2 3 4 5 6 7 8 |
{ "name": "api-demo", "version": "0.0.1", "private": true, "scripts": { "start": "NODE_ENV=development PORT=8081 nodemon ./api.js" } } |
2. ExpressとNodemonのインストール
Express(NodeのWebフレームワーク)とNodemon(変更があった際自動的にサーバーを再起動する技術)をインストールします。
1 |
npm install express nodemon --save-dev |
3. サーバーの起動
開発用サーバーを起動するために、コマンドライン上で以下のコマンドを実行します。
1 |
npm start |
http://127.0.0.1:8081 をUbuntu Desktop内のブラウザで開きましょう。“Hello World” と表示されます。
http://127.0.0.1:8081/fruits を開くと、果物のリストが表示されます。
http://127.0.0.1:8081/abc を開くと、”Error 404 – Not Found” と表示されます。このリンクのページが存在しないためです。
これでAPIが完成しました。
4. フロントエンドとAPIの接続
APIサーバーを起動したままにして、フロントエンドのデモンストレーションプログラムを作成します。
新しくターミナルを起動して以下のコマンドを実行してください。
1 |
cd ~ |
1 |
mkdir sample-frontend-app |
sample-frontend-app
ディレクトリ下で、以下のindex.html
とscript.js
を作成しましょう。
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>API Connection Example</title> </head> <body> <h1>APIと接続するフロントエンドアプリ</h1> <div> <button id="fetchData">データを取得</button> <div id="result"></div> </div> <script src="script.js"></script> </body> </html> |
script.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
document.getElementById('fetchData').addEventListener('click', () => { const resultDiv = document.getElementById('result'); resultDiv.textContent = 'データを取得中...'; // Use API that we have created fetch('http://127.0.0.1:8081/fruits') .then(response => { if (!response.ok) { throw new Error(`HTTPエラー! ステータス: {response.status}`); } return response.json(); }) .then(data => { // get json data resultDiv.textContent = JSON.stringify(data, null, 2); }) .catch(error => { // error message resultDiv.textContent = `エラー: ${error.message}`; }); }); |
ファイルを保存して、以下のコマンドを実行します。
1 |
python3 -m http.server |
http://127.0.0.1:8000/ をUbuntu Desktop内のブラウザで表示して「データを取得」ボタンをクリックすると以下のように表示されるはずです。
{ “apples”: 1, “bananas”: 5, “oranges”: 10 }
以上で、このチュートリアルは終了です。