node實現(xiàn)簡單的增刪改查接口實例代碼
更新時間:2019年08月22日 14:53:36 作者:younger~
在本篇文章里小編給大家整理的是關于node實現(xiàn)簡單的增刪改查接口的相關實例內(nèi)容,有需要的朋友們可以學習下。
node實現(xiàn)簡單的增刪改查接口的全部代碼如下:
// 數(shù)據(jù)存儲在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"); });
以上就是全部相關代碼,大家可以測試下,感謝大家對腳本之家的支持。
相關文章
Webpack 實現(xiàn) Node.js 代碼熱替換
Webpack有一個很實用的功能叫做熱替換(Hot-replace),尤其是結(jié)合React Hot Loader插件,開發(fā)過程中都不需要刷新瀏覽器,任何前端代碼的更改都會實時的在瀏覽器中表現(xiàn)出來。2015-10-10從零開始學習Node.js系列教程三:圖片上傳和顯示方法示例
這篇文章主要介紹了Node.js圖片上傳和顯示方法,結(jié)合實例形式分析了nodejs基于http傳輸圖片文件及顯示圖片的相關實現(xiàn)步驟與操作技巧,需要的朋友可以參考下2017-04-04nodejs async異步常用函數(shù)總結(jié)(推薦)
這篇文章主要介紹了nodejs async異步常用函數(shù)總結(jié)的相關資料,需要的朋友可以參考下2017-11-11