0
0
お題は不問!Qiita Engineer Festa 2024で記事投稿!
Qiita Engineer Festa20242024年7月17日まで開催中!

フロントデータ取得の単純な開発環境

Last updated at Posted at 2024-07-07

はじめに

フロントデータとして位置情報を取得します。
位置情報を取得し、サーバでその情報を取得する所を行います。
まず開発環境で試します。

構成

ローカル環境でAPIサーバーとフロントエンドを連携させて動作確認をします。

  • APIサーバをnodeで作ります。
  • フロントをセットします。
  • HTTPサーバを立ち上げます。

ステップ1: ローカルAPIサーバーのセットアップ

node.jsでサーバとしてセットするために以下のライブラリーが必要になります。

  • express: Node.jsのためのWebアプリケーションフレームワーク。ルーティングやミドルウェアの管理が簡単に行えます。
  • body-parser: Express用のミドルウェアで、リクエストボディのデータを解析して扱いやすくします。
  • cors:Express用のミドルウェアで、異なるオリジンからのHTTPリクエストを許可するためのCORS設定を簡単に追加できます。

1. プロジェクトディレクトリの作成

mkdir local-api-server
cd local-api-server
npm init -y

2. 必要なパッケージのインストール

npm install express body-parser cors

3. APIサーバーの作成

プロジェクトディレクトリに server.js ファイルを作成し、以下の内容を追加します。

server.js
const express = require('express');
const cors = require('cors');
const app = express();
const bodyParser = require('body-parser');

app.use(cors()); // ここでCORSを有効化
app.use(bodyParser.json());

app.post('/api/data', (req, res) => {
    const data = req.body;
    console.log(data);
    res.status(200).send('Data received');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

4. APIサーバーの起動

node server.js

このコマンドでAPIサーバーが起動し、ポート3000でリクエストを受け付けるようになります。

ステップ2: フロントエンドのセットアップ

次に、フロントエンドのHTMLファイルを作成し、APIサーバーにデータを送信できるようにします。

1. プロジェクトディレクトリの作成

別のディレクトリを作成して、その中にHTMLファイルを置きます。

mkdir local-frontend
cd local-frontend

2. HTMLファイルの作成

index.html ファイルを作成し、以下の内容を追加します。

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Geolocation Example</title>
</head>
<body>
    <h1>Geolocation Example</h1>
    <button onclick="getLocation()">Get Location</button>
    <p id="location"></p>

    <script>
        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition, showError);
            } else {
                document.getElementById("location").innerText = "Geolocation is not supported by this browser.";
            }
        }

        function showPosition(position) {
            const coords = {
                latitude: position.coords.latitude,
                longitude: position.coords.longitude
            };
            document.getElementById("location").innerText = 
                "Latitude: " + coords.latitude + ", Longitude: " + coords.longitude;

            sendDataToServer(coords);
        }

        function showError(error) {
            switch(error.code) {
                case error.PERMISSION_DENIED:
                    document.getElementById("location").innerText = "User denied the request for Geolocation.";
                    break;
                case error.POSITION_UNAVAILABLE:
                    document.getElementById("location").innerText = "Location information is unavailable.";
                    break;
                case error.TIMEOUT:
                    document.getElementById("location").innerText = "The request to get user location timed out.";
                    break;
                case error.UNKNOWN_ERROR:
                    document.getElementById("location").innerText = "An unknown error occurred.";
                    break;
            }
        }

        function sendDataToServer(data) {
            fetch('http://localhost:3000/api/data', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.text())
            .then(result => {
                console.log('Success:', result);
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }
    </script>
</body>
</html>

ステップ3:httpサーバ立ち上げ

ローカルサーバーでHTMLファイルを提供

ローカルでHTTPサーバーを立ち上げるのは、Web開発において必要なステップです。これにより、HTML、CSS、JavaScriptファイルを実際の環境でテストし、ブラウザを通じて動作確認を行うことができます。
ローカルでHTMLファイルを確認するためには、簡単なHTTPサーバーを立ち上げます。Pythonを使う例を記述します。

Python 3の場合
python -m http.server 8000

このコマンドを実行すると、index.html ファイルがローカルホストのポート8000で提供されます。

ステップ4: 動作確認

  1. ブラウザで http://localhost:8000 にアクセスします。
  2. 「Get Location」ボタンをクリックして、位置情報の取得とAPIサーバーへのデータ送信を試みます。
  3. ターミナルでAPIサーバーのログを確認し、データが正常に受信されたかどうかを確認します。

おわりに

この手順により、ローカル環境でフロントエンドとバックエンドの連携をテストし、動作確認を行うことができます。

0
0
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
0
0