LoginSignup
0
1

More than 1 year has passed since last update.

【Node.js】Node.jsでAPIを作ってデータを操作する。

Last updated at Posted at 2023-04-21

概要

フロント側から、フォームでデータを送り、Node.js側でJSONファイルを作成して、連想配列で保存していこうと思います。

ソースコード

Node.jsのソースコード

まずは、info.jsonファイルを作成して、データを一つ入れておきます。

info.json
[{"name":"fuku","text":"pass"}]

そして、info.jsonファイルに、ブラウザのフォームから送られてきた内容をJSONファイルに保存するAPIを作成していきます。
細かいコードの説明は、ソースコード内に記述していきます。

app.js
const express = require('express');
const cors = require('cors');
const app = express();
const fs = require('fs')

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// CORSでhttp://localhost:8080からのリクエストを許可
app.use(cors({
  origin: 'http://localhost:8080',
  credentials: true
}));

// POSTメソッドでフォームの値を受け取る
app.post('/api/v1/quiz', (req, res) => {
    try{
        fsで、JSONファイルを指定して、JSONファイルにデータにアクションをかけることができる。
                readFileメソッドは、指定したJSONファイル(今回はinfo.js)を取得することができる。
        fs.readFile('info.json', 'utf8', (err, data) => {
                        エラーが出た場合returnする。
            if (err) {
                console.error(err);
                return;
            }
            // ファイルをJSONパースして配列に変換する
            let arr = JSON.parse(data);
            
            // 新しいオブジェクトを作成して配列に追加する
            arr.push({ name: req.body.name, text: req.body.text });
            
            // 配列をJSON文字列に変換する
            let newData = JSON.stringify(arr);
            
            // writeFileメソッドで、JSONファイルに送られてきたデータを追加する。
            fs.writeFile('info.json', newData, 'utf8', (err) => {
                if (err) {
                    console.error(err);
                    return;
                }
                console.log('JSONデータを追加!');
            });
        });
    }catch(e){
        console.log("error")
    }
});
3000番ポートでサーバーを起動できるようにする。
app.listen(3000, () => console.log('Server running on port 3000'));

フロント側の実装

最後に、JSONファイルにデータを送るための簡単なフォームを作成する。
今回は、フォームに「kenta」、「foo」と入力して、送信ボタンを押しましょう。

TestView.vue
<template>
//POSTメソッドで、Node.js上で作成したAPIにリクエストを送る
  <form action="http://localhost:3000/api/v1/quiz" method="POST" >
    <input type="text" name="name">
    <input type="text" name="text">
    <button type="submit">送信</button>
  </form>
</template>

すると....

info.json
[{"name":"fuku","text":"pass"},{"name":"kenta","text":"foo"}]

このように、フォームに入力したデータがJSONファイルに連想配列で格納されました!

データの取得

次は、先ほど保存したデータをフロント側から取得したいと思います。
まずは、Node.jsにJSONファイルからデータを取得するAPIを作成していきます。

app.js
app.get('/api/v1/quiz', (req, res) => {
  try{
      //データを取りだす
      const bufferData = fs.readFileSync('info.json')
      // データを文字列に変換
      const dataJSON = bufferData.toString()
      //JSONのデータをJavascriptのオブジェクトに
      const data = JSON.parse(dataJSON)
      console.log(data)
      res.send(data)
  }catch(e){
      console.log("JSONデータなし")
  }
});

次に、フロント側でデータを取得するリクエストを送るボタンを作成して、リクエストを送るメソッドを追記します。

TestView.vue
<template>
<form action="http://localhost:3000/api/v1/quiz" method="POST" >
    <input type="text" name="name">
    <input type="text" name="text">
    <button type="submit">送信</button>
</form>
<button @click="reception">JSONデータをもらう</button>
</template>

<script>
import axios from 'axios'
export default {
    methods: {
        reception(){
        axios.get("http://localhost:3000/api/v1/quiz")
            .then(response => {
            console.log(response.data)
            })
            .catch(error => {
            console.log(error)
            })
        }
    }
}
</script>

Axiosは、フロントからAPI通信を簡単な記述で行えるようにするライブラリです。
ちなみに、今回取得するJSONファイルの内のデータはこちらです。

info.json
[{"name":"fuku","text":"pass"},{"name":"kenta","text":"foo"},{"name":"yama","text":"debu"}]

これでJSONファイル内のデータをAPIを介して、取得する準備ができました。それでは、ボタンを押してみましょう。
すると...
スクリーンショット 2023-04-22 20.38.15.png
このように、フロント側で取得することができました!

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