🐈 【Node.js、Express】バックエンドサーバー6(2章までのコード)
作成日: 2022/05/01
1

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>coronaDate</title>
</head>
<body>
  <h1>日本の季節</h1>
  <p>秋は行楽シーズンで、たくさんの人が観光にでかける。</p>
  <h3>POST(投稿)</h3>
  <form action="/autumn" method="POST">
    <input type="text" name="activity">
    <button type="submit">投稿</button>
  </form>
  <br><br>
  <hr>
  <br>
  <h3>PUT(更新)</h3>
  <form action="/update" method="POST">
    <input type="text" name="updateActivity">
    <button type="submit">変更</button>
  </form>
  <br><br>
  <hr>
  <br>
  <h3>DELETE(削除)</h3>
  <form action="/delete" method="POST">
    <input type="radio" name="number" value="0" id="one">
    <label for="one">1</label>
    <br>
    <input type="radio" name="number" value="1" id="two">
    <label for="two">2</label>
    <br>
    <input type="radio" name="number" value="2" id="three">
    <label for="three">3</label>
    <br>
    <button type="submit">削除</button>
  </form>
  <br><br>
  <hr>
  <br>
  <h3>LINK</h3>
  <p><a href="./autumn">autumn</a></p>
  <p><a href="./update">update</a></p>
</body>
</html>

index.js

const fs = require('fs');
const express = require("express");
const activities = require("./activities.json");
const app = express();
// const coronaData = require("./coronaData.json");
app.use(express.urlencoded({ extended: true }));

/* ----- index読み込み ----- */
app.get("/", function (req, res) {
  res.sendFile(__dirname + "/index.html");
});

/* ----- autumnファイル書き込み(投稿) ----- */
app.post("/autumn", function (req, res) {
  fs.writeFile(__dirname + "/data.txt", req.body.activity, function() {
    res.send("投稿完了");
  });
});

/* ----- データの変更 ----- */
app.post("/update", function (req, res) {
  activities[0].activity = req.body.updateActivity;
  res.send(activities);
});

/* ----- データの削除 ----- */
app.post("/delete", function (req, res) {
  activities.splice(req.body.number, 1);
  res.send(activities);
})

/* ----- バックエンドサーバーとブラウザをつなぐ ----- */
app.listen(5000, function() {
  console.log("Listeningonlocalhostport5000");
})

activities

[
  {
    "activities": "いちご狩り"
  },
  {
    "activities": "バイキング"
  },
  {
    "activities": "芸術鑑賞"
  }
]

package.json

{
  "name": "express",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.3"
  }
}

画面
スクリーンショット 2022-05-01 12.44.58.png