node实现简单的增删改查接口实例代码
更新时间:2019年08月22日 14:53:36 作者:younger~
在本篇文章里小编给大家整理的是关于node实现简单的增删改查接口的相关实例内容,有需要的朋友们可以学习下。
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"); });
以上就是全部相关代码,大家可以测试下,感谢大家对脚本之家的支持。
相关文章
npm does not support Node.js问题的解决办法
这篇文章主要给大家介绍了关于npm does not support Node.js问题的解决办法,文中通过代码以及图文介绍的非常详细,对大家的学习或者工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-10-10Node.js基础入门之path模块,url模块,http模块使用详解
这篇文章主要为大家介绍了Node.js中的三个模块(path、url、http)的使用详解,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下2022-03-03
最新评论