node实现简单的增删改查接口实例代码
程序员文章站
2022-04-09 12:40:35
node实现简单的增删改查接口的全部代码如下:
// 数据存储在users.json文件中
const express = require("express")...
node实现简单的增删改查接口的全部代码如下:
// 数据存储在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"); });
以上就是全部相关代码,大家可以测试下,感谢大家对的支持。