遵循Restful规范的简单的栗子

  • 前端代码:
<html><head><script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script><script src="https://unpkg.com/element-ui/lib/index.js"></script><script src="https://unpkg.com/axios/dist/axios.min.js"></script><link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css" /></head><body><div id="app"><div style="display: flex;flex-direction: column;"><el-input v-model="form.name" autocomplete="off" placeholder="姓名" style=""></el-input><el-button v-on:click="get">GET</el-button><el-button v-on:click="post">POST</el-button><el-button v-on:click="del">DELETE</el-button><el-button v-on:click="put">PUT</el-button><el-button v-on:click="logs=[]">Clear Log</el-button></div><!-- 日志部分 --><ul><li v-for="(log, idx) in logs" :key="idx">{{log}}</li></ul></div><script>axios.defaults.baseURL = "http://localhost:3000";axios.interceptors.response.use(response => {app.logs.push(JSON.stringify(response.data));return response;},err => {app.logs.push(JSON.stringify(response.data));return Promise.reject(err);})var app = new Vue({el: '#app',data: {form: {name: 'marron',id: 3},logs: []},methods: {async post() {const res = await axios.post("/users", this.form);},async get() {const res = await axios.get("/users");},async put() {const res = await axios.put("/users", this.form);},async del() {const res = await axios.delete("/users/3");}}})</script>
</body></html>
  • 后端代码
const Koa = require("koa");
const app = new Koa();
const Router = require("koa-router");
const router = new Router({ prefix: "/users" });
const cors = require("koa2-cors");
const bodyParser = require("koa-bodyparser");
app.use(cors());
app.use(bodyParser());const users = [{id:1 , name:"tom"}, {id:2, name: "jerry"}];// 查找数据  ?name = xx
router.get("/", ctx =>{console.log("GET /users");const {name} = ctx.query;  // ?name = xxlet data = users;if (name) {data = users.filter (u => u.name === name);}ctx.body = {ok: 1, data};
});// 查找数据  /users/1   id = 1
router.get("/:id", ctx =>{console.log("GET /users/:id");const {id} = ctx.params;  // /users/1const data = users.find(u => u.id == id);ctx.body = {ok:1 , data};
});// 新增用户
router.post("/", ctx=>{console.log("POST /users");const {body: user} = ctx.request; // 请求bodyuser.id = users.length +1;users.push(user);ctx.body = { ok: 1};
});router.put("/", ctx => {console.log("PUT /users");const {body: user} = ctx.request;   // 请求bodyconst idx = users.findIndex(u => u.id == user.id);if(idx > -1){users[idx] = user;}ctx.body = { ok: 1};
});// 删除用户 /users/1  删除id为1
router.delete("/:id", ctx =>{console.log("DELETE /users/:id");const {id} = ctx.params;const idx  = users.findIndex(u => u.id === id);if( idx > -1){users.splice(idx, 1);}ctx.body ={ ok: 1};
});app.use(router.routes());
app.listen(3000, ()=>{console.log("[Server] Server is running at http://localhost:3000");
})

Restful规范几个注意:

  1. 动宾结构
    客户端发出的指令都是"动词 + 宾语"的结构,如: “GET / articles”
  2. 动词的覆盖
    可以使用 X-HTTP-Method-Override属性告诉服务器使用哪一个动词覆盖POST方法
POST /api/marron/1 HTTP/1.1
X-HTTP-Method-Override: PUT

上面指明了PUT方法.
在服务器端(koa2)使用下面方法接受

router.put("/api/marron:id", async ctx=>{})
  1. 宾语必须是名词,且尽量为复数
    不要出现/getnames/name之类的,尽量使用 /names
  2. 尽量扁平化
    不要出现GET /authors/12/categories/2 ,如果可以,尽量使用GET /authors/12?categories=2

koa --- restful规范及其栗子相关推荐

  1. Django框架深入了解_01(Django请求生命周期、开发模式、cbv源码分析、restful规范、跨域、drf的安装及源码初识)

    阅读目录 一.Django请求生命周期: 二.WEB开发模式: 三.cbv源码分析: 四.认识RESTful 补充知识:跨域 五.基于原生django开发restful的接口 六.drf安装.使用.A ...

  2. drf1 rest restful规范

    web服务交互 我们在浏览器中能看到的每个网站,都是一个web服务.那么我们在提供每个web服务的时候,都需要前后端交互,前后端交互就一定有一些实现方案,我们通常叫web服务交互方案.目前主流的三种w ...

  3. restful规范和APIView

    django生命周期 1.先进入wsgi协议的web服务器2.进入django的中间件3.路由4.视图5.取模板,取数据,用数据渲染模板6.返回模板的字符串7.在wsgi中封装后发送给浏览器 开发模式 ...

  4. Django之 RESTful规范

    RESTful 规范 一.什么是RESTful REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为"表征 ...

  5. php restful规范,RESTFul API规范 详细指南

    RESTFul规范 RESTFul是一种HTTP API接口规范,只要满足的RESTFul规范,即可称为RESTFul API. 既然是接口,我们先来了解一下,他和传统的API接口有何不同吧. 本文以 ...

  6. Django RESTful规范

    Restful : web服务交互: 我们在浏览器中能看到的每个网站, 都是一个web服务. 那么我们在提供每个web服务的时候, 都需要前后端交互. 前后端交互就一定有一些实现方案, 我们通常叫we ...

  7. Restful规范-开发api接口

    web服务交互 我们在浏览器中能看到的每个网站,都是一个web服务.那么我们在提供每个web服务的时候, 都需要前后端交互,前后端交互就一定有一些实现方案,我们通常叫web服务交互方案. 目前主流的三 ...

  8. Drf从入门到精通一(API接口、Postman、Restful规范、序列化、快速使用drf、CBV源码分析)

    文章目录 一.前后端开发模式 二.API接口 三.接口测试工具Postman 四.Restful规范 五.序列化反序列化 六.DjangoRestFramework快速使用 七.CBV源码分析 一.前 ...

  9. REST-Framework: RESTful规范

    目录 一 什么是RESTful 二  RESTful API设计 三 基于原生的Django实现 一 什么是RESTful REST与技术无关,代表的是一种软件架构风格,REST是Representa ...

最新文章

  1. Google发布三大新品,Pixel手机价格直逼苹果
  2. 键盘上每个键作用!!!
  3. 编写有效的事条指导原则
  4. server的自增主键返回函数 sql_mybatis+sqlserver中返回非自增主键
  5. json - 如何在 flutter 中的List String中加入2 json值?
  6. WordPress的MySQL宕_wordpress数据库mysql使用phpmyadmin打开数据表,提示table “xxx” doesn`t exist...
  7. Linux有问必答:如何在树莓派上安装USB网络摄像头
  8. onload与ready差异
  9. pycharm:Updating Indices 解决办法
  10. Springboot整合SpringSecurity 04-启用登出logout功能
  11. RestoreDet
  12. 关于CNN中出现的诸如conv4_3、conv8_2、conv7等标识的含义
  13. 贝叶斯决策理论之入门篇
  14. Orleans 2.0 官方文档 —— 4.1 Grains - 开发一个Grain
  15. OpenCV C++案例实战六《绿幕视频背景替换》
  16. 交通信号灯控制系统的Verilog实现
  17. bzoj 2081: [Poi2010]Beads 哈希
  18. HDU 1220 正方体问题
  19. SQL Server的备份
  20. 果里果气的套壳Windows11系统资源来了,已跳过TPM安全模块验证

热门文章

  1. java 向上抛异常_java throws 向上抛出的概念问题
  2. binaryformatter java_Java,C#使用二进制序列化、反序列化操作数据
  3. body 没有被撑开_body没有高度设置背景色为什么可以全屏显示?
  4. C# int[,] 和 int[][]
  5. hive币2021年预计涨到多少_比特币突破4万美元,比特币2021年会涨到多少?
  6. [UE4]C++中extern关键字浅谈
  7. Oauth2.0和1.0区别
  8. runtime--实现篇02(Category增加属性)
  9. 在oracle中使用Trigger
  10. TWRP-recovery中文界面安装方法[转]