// 对本地数据user.json进行增删改查 const express = require('express'); const fs = require("fs"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.urlencoded({extended: false})) app.use(bodyParser.json()); //设置跨域访问 app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "*"); res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); res.header("Content-Type", "application/json;charset=utf-8"); next(); }); /** * 随机生成id * @returns {string} */ function guid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } // 查询 app.get("/userlist", function(req, res) { fs.readFile("user.json", "utf8", function(err, data) { res.end(data); }); }); //新增 app.post("/adduser",function(req,res){ fs.readFile("user.json", "utf8", (err, data) => { if (err) {throw err;} params={ "name":req.body.name, "age":req.body.age, "id":guid() } var person = data.toString();//将二进制的数据转换为字符串 person = JSON.parse(person);//将字符串转换为json对象 person.push(params); var str = JSON.stringify(person); fs.writeFile("user.json", str, err => { if(err){throw err;} res.end(); }); }); }); // 删除 app.post("/delUser/:id", (req, res) => { const id = req.params.id; fs.readFile("user.json", "utf8", (err, data) => { data = JSON.parse(data) || []; const saveData = data.filter((item)=>{ return item.id !== id; }); fs.writeFile("user.json", JSON.stringify(saveData), err => { if (err) throw err; res.end(); }); }); }); // 修改 app.post("/update", (req, res) => { const id = req.body.id; const body = req.body; fs.readFile("user.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("user.json", JSON.stringify(userList), err => { if (err) throw err; res.end(); }); }); }); //配置服务端口 var server = app.listen(3000, function() {}) //备注:修改和删除接口无法对比前台传过来的id,原因是因为新增的时候没有id,当全部删除之后,新增数据的时候,就没有id,从而无法比较