使用node怎么实现一个增删改查接口-创新互联

使用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");
});

看完上述内容,你们掌握使用node怎么实现一个增删改查接口的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


分享文章:使用node怎么实现一个增删改查接口-创新互联
网站URL:http://pwwzsj.com/article/ddgdjc.html