0
0

node.jsを使ってログインサーバーを作る(?)

Posted at

初めに

今回はnode.jsを使ってログインサーバーを作ります(?)

注意

今回はnode.jsを使用します。node.jsをダウンロードしていない方は以下のリンクからnode.jsをダウンロードしてください(クリックしたら自動的にインストーラーがダウンロードされます)
Node.jsダウンロード(Windows)

ファイル構成

今回のファイル構成は以下にあるとおりです

|
|--public
|      |---index.html
|      |---login.js
|
|--server.js

モジュールのダウンロード

まず、コマンドプロンプトで以下のコマンドを入力してください

cmd
cd C:\Users\Your_name\Downloads\Your_projectName

※...Your_nameとYour_projectNameは自分のものに置き換えてください(例えば自分だと以下のようになります)

cmd
cd C:\Users\qqn5192\Downloads\loginserver

実行したら以下のコマンドを入力してください:

cmd
npm init -y

実行したらプロジェクトのフォルダー直下にpackage.jsonが作成されていると思います。(間違ってたらすみません)
実行したら以下の2つのコマンドを入力してください

cmd
npm install express body-parser

npm install cors

そしたらプロジェクトフォルダー直下にpackage-lock.jsonが作成されると思います。(多分)
express body-parserは多分サーバー用のもので、corsは通信時のcorsエラーを回避するために使用します

コピペ

早速以下のコードをコピペしてください

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

const app = express();
const port = 3000;

app.use(cors()); // CORS を設定
app.use(bodyParser.json()); // JSON ボディをパース
app.use(express.static('public')); // HTML ファイルを提供する設定

// POST /login エンドポイントの設定
app.post('/login', (req, res) => {
    const { user, pass } = req.body;

    if (user === 'testuser' && pass === 'testpass') {
        res.status(200).json({ message: 'ログイン成功' });
    } else {
        res.status(401).json({ message: 'ログイン失敗' });
    }
});

app.listen(port, () => {
    console.log(`サーバーが http://localhost:${port} で起動しました`);
});

login.js:

login.js
function login() {
    const box = document.getElementById('Username');
    const pass = document.getElementById('pass');
    
    if (box !== null && pass !== null) {
        const authData = {
            user: box.value,
            pass: pass.value
        };
        
        fetch('http://localhost:3000/login', { // サーバーのポートに合わせる
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(authData)
        })
        .then(response => {
            if (!response.ok) {
                return response.text().then(text => {
                    throw new Error(`サーバーエラー: ${response.status} - ${text}`);
                });
            }
            return response.json();
        })
        .then(data => {
            alert('ログイン成功');
        })
        .catch(error => {
            alert('エラー: ' + error.message);
        });
    } else {
        alert('エラー:ログイン情報が欠損しています');
    }
}

index.html:

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ログイン</title>
    <script src="login.js" defer></script>
</head>
<body>
    <center>
        <h2>ログイン</h2>
        <p>ユーザー名</p>
        <input type="text" id="Username">
        <p>パスワード</p>
        <input type="password" id="pass">
        <br><button style="margin-top: 20px;" onclick="login()">ログイン</button>
    </center>
</body>
</html>

コピペしたら、以下のコマンドを実行してください

cmdまたはvscodeのターミナル
node server.js

実行して「ポートがlocalhost:3000で起動しました」みたいなことが出てきたら完成です(このプログラムを動作させるときは毎回node server.jsを実行してください。そうしないとエラーが起きて動作しません)

最後に

いかがだったでしょうか?今回は初めてnode.jsを使ってログインサーバーを作ってみました、ちなみにnode.jsのほうはchatgptにいろいろ教えてもらいながら作りました。
それではまたお会いしましょう!

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