node实现简单的增删改查接口实例代码
node实现简单的增删改查接口的全部代码如下:
//数据存储在users.json文件中
constexpress=require("express");
constfs=require("fs");
constcors=require("cors");
constbodyParser=require("body-parser");
constapp=express();
app.use(cors({origin:"*"}));//fix跨域
app.use(bodyParser.json());//forparsingapplication/json
app.use(bodyParser.urlencoded({extended:true}));//forparsingapplication/x-www-form-urlencoded
//新增
app.post("/addUser",(req,res)=>{
fs.readFile("./users.json","utf8",(err,data)=>{
if(err){
throwerr;
}
data=data?JSON.parse(data):[];
data.push(req.body);
fs.writeFile("./users.json",JSON.stringify(data),err=>{
if(err)throwerr;
res.end();
});
});
});
//删除
app.delete("/delUser/:id",(req,res)=>{
constid=req.params.id;
fs.readFile("./users.json","utf8",(err,data)=>{
data=JSON.parse(data)||[];
constsaveData=data.filter(item=>item.id!=id);
fs.writeFile("./users.json",JSON.stringify(saveData),err=>{
if(err)throwerr;
res.end();
});
});
});
//修改
app.put("/update/:id",(req,res)=>{
constid=req.params.id;
constbody=req.body;
fs.readFile(__dirname+"/"+"users.json","utf8",(err,data)=>{
constuserList=(data&&JSON.parse(data))||[];
constindex=userList.findIndex(item=>item.id==id);
userList[index]={...userList[index],...body};
fs.writeFile("./users.json",JSON.stringify(userList),err=>{
if(err)throwerr;
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");
});
以上就是全部相关代码,大家可以测试下,感谢大家对毛票票的支持。