使用node怎么實現(xiàn)一個增刪改查接口?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
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"); });
看完上述內(nèi)容,你們掌握使用node怎么實現(xiàn)一個增刪改查接口的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
文章名稱:使用node怎么實現(xiàn)一個增刪改查接口-創(chuàng)新互聯(lián)
網(wǎng)站地址:http://chinadenli.net/article22/ddgdjc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供營銷型網(wǎng)站建設(shè)、響應(yīng)式網(wǎng)站、外貿(mào)網(wǎng)站建設(shè)、網(wǎng)站導(dǎo)航、全網(wǎng)營銷推廣、面包屑導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容