首页 > 其他 > 详细

node实现简单的增删改查接口

时间:2019-08-22 14:39:59      阅读:213      评论:0      收藏:0      [点我收藏+]
// 数据存储在users.json文件中
const express = require("express");
const fs = require("fs");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();

app.use(cors({ origin: "*" })); // fix 跨域
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

// 新增
app.post("/addUser", (req, res) => {
  fs.readFile("./users.json", "utf8", (err, data) => {
    if (err) {
      throw err;
    }
    data = data ? JSON.parse(data) : [];
    data.push(req.body);
    fs.writeFile("./users.json", JSON.stringify(data), err => {
      if (err) throw err;
      res.end();
    });
  });
});

// 删除
app.delete("/delUser/:id", (req, res) => {
  const id = req.params.id;
  fs.readFile("./users.json", "utf8", (err, data) => {
    data = JSON.parse(data) || [];
    const saveData = data.filter(item => item.id != id);
    fs.writeFile("./users.json", JSON.stringify(saveData), err => {
      if (err) throw err;
      res.end();
    });
  });
});

// 修改
app.put("/update/:id", (req, res) => {
  const id = req.params.id;
  const body = req.body;
  fs.readFile(__dirname + "/" + "users.json", "utf8", (err, data) => {
    const userList = (data && JSON.parse(data)) || [];
    const index = userList.findIndex(item => item.id == id);
    userList[index] = { ...userList[index], ...body };
    fs.writeFile("./users.json", JSON.stringify(userList), err => {
      if (err) throw err;
      console.log("修改");
      res.end();
    });
  });
});

// 列表查询
app.get("/listUsers", function(req, res) {
    fs.readFile(__dirname + "/" + "users.json", "utf8", function(err, data) {
      console.log(data);
      res.end(data);
    });

});


app.listen(8081, function() {
  console.log("访问地址: http://localhost:8081");
});

 

node实现简单的增删改查接口

原文:https://www.cnblogs.com/hlandzpy/p/11394143.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!