使用node.js,Bootstrap,axios实现增删改查存取数据带自写接口

使用node.js,Bootstrap,axios实现增删改查存取数据带自写接口_第1张图片使用node.js,Bootstrap,axios实现增删改查存取数据带自写接口_第2张图片
index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>列表</title>
    <!-- Latest compiled and minified CSS -->
    <link
      rel="stylesheet"
      href="http://netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"
    />
  </head>
  <body class="container">
    <div class="panel panel-info">
      <div class="panel-heading">
        <h3 class="panel-title">萌宠列表</h3>
      </div>
      <div class="panel-body">
        <a href="/new.html" class="btn btn-danger btn-sm">新增</a>

        <table class="table table-bordered table-striped table-hover">
          <thead>
            <tr>
              <th>序号</th>
              <th>头像</th>
              <th>名称</th>
              <th>技能</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody id="list"></tbody>
        </table>
      </div>
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.min.js"></script>
    <script>
      axios.get("/api/v1/pets").then((res) => {
        var strHtml = "";
        res.data.forEach((pet, index) => {
          strHtml += `<tr>
              <td>${index + 1}</td>
              <td>${pet.name}</td>
              <td><img src="${
                pet.img
              }" style="width: 80px; max-height: 80px;"/></td>
              <td>${pet.skills}</td>
              <td>
                <button onclick="delOne('${
                  pet.id
                }')" class="btn btn-danger btn-sm">删除</button>
                <a class="btn btn-info btn-sm" href="/edit.html?id=${
                  pet.id
                }">修改</a>
              </td>
            </tr>`;
        });
        document.querySelector("#list").innerHTML = strHtml;
      });

      function delOne(id) {
        if (confirm("是否确认删除此项")) {
          // 删除操作
          //  参数一 为地址
          axios.delete("/api/v1/pets/" + id).then((res) => {
            window.location.reload();
          });
        }
      }
    </script>
  </body>
</html>

new.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>新增</title>
    <!-- Latest compiled and minified CSS -->
    <link
      rel="stylesheet"
      href="http://netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"
    />
  </head>
  <body class="container">
    <div class="panel panel-info">
      <div class="panel-heading">
        <h3 class="panel-title">萌宠新增</h3>
      </div>
      <div class="panel-body">
        <legend>数据新增</legend>
        <div class="form-group">
          <label for="">名字</label>
          <input
            type="text"
            class="form-control"
            id="txtName"
            placeholder="请输入名字"
          />
        </div>
        <div class="form-group">
          <label for="">头像</label>
          <input
            type="text"
            class="form-control"
            id="txtImg"
            placeholder="请输入头像"
          />
        </div>
        <div class="form-group">
          <label for="">技能</label>
          <textarea
            class="form-control"
            id="txtSkills"
            placeholder="请输入技能"
            rows="3"
          ></textarea>
        </div>
        <button onclick="saveHandle()" class="btn btn-primary btn-block">
          提交
        </button>
      </div>
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.min.js"></script>
    <script>
      function saveHandle() {
        var name = document.querySelector("#txtName").value;
        var img = document.querySelector("#txtImg").value;
        var skills = document.querySelector("#txtSkills").value;
        if (name && img && skills) {
          axios
            .post("/api/v1/pets", {
              name,
              img,
              skills,
            })
            .then((res) => {
              // console.log(res);
              window.location.href = "/index.html";
            });
        } else {
          alert("请输入指定的内容");
        }
      }
    </script>
  </body>
</html>

edit.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>新增</title>
    <!-- Latest compiled and minified CSS -->
    <link
      rel="stylesheet"
      href="http://netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"
    />
  </head>
  <body class="container">
    <div class="panel panel-info">
      <div class="panel-heading">
        <h3 class="panel-title">萌宠新增</h3>
      </div>
      <div class="panel-body">
        <legend>数据修改</legend>
        <div class="form-group">
          <label for="">名字</label>
          <input
            type="text"
            class="form-control"
            id="txtName"
            placeholder="请输入名字"
          />
        </div>
        <div class="form-group">
          <label for="">头像</label>
          <input
            type="text"
            class="form-control"
            id="txtImg"
            placeholder="请输入头像"
          />
        </div>
        <div class="form-group">
          <label for="">技能</label>
          <textarea
            class="form-control"
            id="txtSkills"
            placeholder="请输入技能"
            rows="3"
          >
          </textarea>
        </div>
        <button onclick="saveHandle()" class="btn btn-primary btn-block">
          提交
        </button>
      </div>
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.min.js"></script>
    <script>
      // URLSearchParams可以获取当前url中的search值,通过get方法
      var params = new URLSearchParams(window.location.search);
      var id = params.get("id");
      var txtName = document.querySelector("#txtName");
      var txtImg = document.querySelector("#txtImg");
      var txtSkills = document.querySelector("#txtSkills");
      // console.log(id);
      axios.get("/api/v1/pets/" + id).then((res) => {
        // console.log(res.data);
        txtName.value = res.data.info.name;
        txtImg.value = res.data.info.img;
        txtSkills.value = res.data.info.skills;
      });
      function saveHandle() {
        axios
          .put("/api/v1/pets/" + id, {
            name: txtName.value,
            img: txtImg.value,
            skills: txtSkills.value,
          })
          .then((res) => {
            console.log(res);
            window.location.href = "/index.html";
          });
      }
    </script>
  </body>
</html>

pets.js

const router = require("express").Router();
const fs = require("fs");

// /api/v1/pets
router.get("/", (req, res) => {
  if (fs.existsSync("./db/pets.json")) {
    const str = fs.readFileSync("./db/pets.json").toString();
    res.json(JSON.parse(str));
  } else {
    fs.writeFileSync("./db/pets.json", "[]");
    res.json([]);
  }
});

// /api/v1/pets/1
router.get("/:id", (req, res) => {
  const pets = JSON.parse(fs.readFileSync("./db/pets.json").toString());
  const pet = pets.find((item) => item.id == req.params.id);
  res.json({
    code: 1,
    info: pet ? pet : {},
  });
});

router.post("/", (req, res) => {
  const pets = JSON.parse(fs.readFileSync("./db/pets.json").toString());
  pets.push({ id: Date.now(), ...req.body });
  fs.writeFileSync("./db/pets.json", JSON.stringify(pets));
  res.json({
    code: 1,
    msg: "新增数据成功",
  });
});

router.put("/:id", (req, res) => {
  const pets = JSON.parse(fs.readFileSync("./db/pets.json").toString());
  const index = pets.findIndex((item) => item.id == req.params.id);
  pets[index] = { id: req.params.id, ...req.body };
  fs.writeFileSync("./db/pets.json", JSON.stringify(pets));
  res.json({
    code: 1,
    msg: "修改数据成功",
  });
});

router.delete("/:id", (req, res) => {
  const pets = JSON.parse(fs.readFileSync("./db/pets.json").toString());
  const index = pets.findIndex((item) => item.id == req.params.id);
  pets.splice(index, 1);
  fs.writeFileSync("./db/pets.json", JSON.stringify(pets));
  res.json({
    code: 1,
    msg: "删除数据成功",
  });
});

module.exports = router;

add.js

const express = require("express");
const app = express();
app.use(express.json());
const fs = require("fs");
if (!fs.existsSync("./db")) {
  fs.mkdirSync("./db");
}

app.use("/", express.static("./public"));

app.use("/api/v1/pets", require("./routes/api/v1/pets.js"));
app.use("/api/v1/movies", require("./routes/api/v1/movies.js"));

app.listen(3336, () => {
  console.log("服务器运行在3335端口");
});

package.json

{
  "name": "day3",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

列表创建方式
使用node.js,Bootstrap,axios实现增删改查存取数据带自写接口_第3张图片

你可能感兴趣的:(nodejs)