Fork me on GitHub

Coding Poineer

Coding Poineer

Coding Poineer

Coding Poineer

Coding Poineer

Coding Poineer

Coding Poineer

Coding Poineer

Coding Poineer

Coding Poineer

Coding Poineer

restful API rest设计风格

理清restful API 基本含义
小结:

符合rest设计规范的应用就是使用了restful API

Node搭建 rest风格服务器代码:

var express = require('express');
var app = express();
var fs = require("fs");
const path = require("path")

app.get('/listUsers', function (req, res) {
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
       res.end( data );
   });
})

var user4 = {
  "name" : "add",
  "password" : "123",
  "profession" : "teacher",
  'id' : 4
}
app.get('/addUser', function(req,res){
  fs.readFile(path.join(__dirname,"/users.json"), "utf-8",function(err,data){
    data = JSON.parse(data)
    data.user4 = user4
    data = JSON.stringify(data)
    res.end(data)
    fs.writeFile(path.join(__dirname,"/users.json"),data,function(){})
  })
})

app.get('/:id' , function(req,res){
  const id = req.params.id
  fs.readFile(path.join(__dirname,"/users.json"), "utf-8",function(err,data){
    // 网络接收json文件,转换成js数据
    data = JSON.parse(data)
    data = data['user'+id]
    // 服务器发送出去只能是json文件
    data = JSON.stringify(data)
    res.end(data)
  })
})
//   http://localhost:8081/deleteUser/2
app.get('/deleteUser/:id' , function(req,res){
  const id = req.params.id
  fs.readFile(path.join(__dirname,"/users.json"), "utf-8",function(err,data){
    data = JSON.parse(data)
    // 俏皮,非要这么删除
    delete data["user" + id];
    data = JSON.stringify(data)
    fs.writeFile('/users.json',data,function(){})
    res.end(data)
  })
})

var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("应用实例,访问地址为 http://%s:%s", host, port)
})

users.json

{"user1":{"name":"mahesh","password":"password1","profession":"teacher","id":1},"user2":{"name":"suresh","password":"password2","profession":"librarian","id":2},"user3":{"name":"ramesh","password":"password3","profession":"clerk","id":3},"user4":{"name":"add","password":"123","profession":"teacher","id":4}}

posted @ 2020-11-09 15:32  365/24/60  阅读(92)  评论(0编辑  收藏  举报