koa --- restful規范及其栗子

遵循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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/250499.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/250499.shtml
英文地址,請注明出處:http://en.pswp.cn/news/250499.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

軟工五:四則運算

題目要求 本次作業要求兩個人合作完成&#xff0c;駕駛員和導航員角色自定&#xff0c;鼓勵大家在工作期間角色隨時互換&#xff0c;這里會布置兩個題目&#xff0c;請各組成員根據自己的愛好任選一題。 題目一&#xff1a; 我們在剛開始上課的時候介紹過一個小學四則運算自動生…

Tomcat 配置Https

https://www.cnblogs.com/wanghaoyuhappy/p/5267702.html JDK1.8 keytool 生存證書 C:\keys\tomcat.keystore 1:證書生成 命令如下: keytool -genkey -alias tomcat -keypass 123456 -keyalg RSA -keysize 1024 -keystore C:/keys/tomcat.keytore -storepass 123456 keytool 使…

koa --- 使用koa-multer和element-ui組件上傳頭像

文件上傳 前端代碼 <script src"https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src"https://unpkg.com/element-ui/lib/index.js"></script> <linkrel"stylesheet"href"https://unpkg.co…

PKUSC2018訓練日程(4.18~5.30)

(總計:共66題) 4.18~4.25&#xff1a;19題 4.26~5.2&#xff1a;17題 5.3~5.9: 6題 5.10~5.16: 6題 5.17~5.23: 9題 5.24~5.30: 9題 4.18 [BZOJ3786]星系探索(偽ETT) [BZOJ4337][BJOI2015]樹的同構(樹的最小表示法) [BZOJ3551][ONTAK2010]Peaks(加強版)(Kruskal重構樹,主席樹) …

筆記:less的三種使用方法

直接在瀏覽器端使用 第一步&#xff0c;引入 .less 文件&#xff08;注意要將 rel 屬性設置為“stylesheet/less”&#xff09; <link rel"stylesheet/less" type"text/css" href"styles.less" /> 第二步&#xff0c;引入Less.js文件 <…

koa --- nunjucks在Koa中的使用、中間件的配置

Nunjucks在Koa中的應用 app.js const koa require(koa); const app new koa(); const router require(./router) const nunjucks require(koa-nunjuncks-2); app.use(nunjucks({ext: html, // 指定視圖文件默認后綴path: path.join(__dirname, views), // 指定視圖目錄…

2018福大軟工實踐第六次作業

目錄 NABCD分析引用N(Need&#xff0c;需求)&#xff1a;A(Approach&#xff0c;做法)&#xff1a;B(Benefit&#xff0c;好處)&#xff1a;C(Competitors&#xff0c;競爭)&#xff1a;D(Delivery&#xff0c;交付)&#xff1a;初期中期個人貢獻分評定原則評定細則本組現場答辯…

day32—CSS多列布局學習

轉行學開發&#xff0c;代碼100天——2018-04-17 關于多列布局&#xff0c;前期已經梳理過&#xff0c;今天的培訓課程學習中再次提及&#xff0c;趁此也做個總結和檢驗。 多列布局的介紹參考&#xff1a; day08—css布局解決方案之多列布局關于多列布局的類型和方法&#xff1…

JDBC 事物處理

JDBC 事物處理 ?事務&#xff1a;指構成單個邏輯工作單元的操作集合 ?事務處理&#xff1a;保證所有事務都作為一個工作單元來執行&#xff0c;即使出現了故障&#xff0c;都不能改變這種執行方式。當在一個事務中執行多個操作時&#xff0c;要么所有的事務都被提交(commit…

centos6上安裝mysql8.0版本

本博客是采用yum源的方式安裝&#xff0c;非常的方便和快捷。(redhat 與centos7 等操作系統都可以采用此方法&#xff0c;步驟大體一致) mysql官網地址: https://dev.mysql.com 開始安裝&#xff1a; 1.清理環境&#xff0c;查看有沒有之前安裝過的mysql記錄&#xff0c;清理…

koa --- 使用koa-multer上傳文件+elementUI

核心代碼 const upload require(koa-multer) ({dest: ./public/images}); router.post(/upload, upload.single(file), ctx>{console.log(file, ctx.req.file);console.log(body, ctx.req.body);ctx.body 上傳成功; })目錄結構如下 基本思路 1.通過瀏覽器訪問url: http:…

[bzoj4003][JLOI2015]城池攻占_左偏樹

城池攻占 bzoj-4003 JLOI-2015 題目大意&#xff1a;一顆n個節點的有根數&#xff0c;m個有初始戰斗力的騎士都站在節點上。每一個節點有一個standard&#xff0c;如果這個騎士的戰斗力超過了這個門檻&#xff0c;他就會根據城池的獎勵增加自己的戰斗力。具體地&#xff1a;每一…

Java Web Servlet

Java Web Servlet Servlet是在服務器上運行的小程序。一個Servlet就是一個Java類&#xff0c;并且可以通過“請求-響應”編程模型來訪問的這個駐留在服務器內存里的Servlet程序。 Servlet可完成以下功能&#xff1a; 讀取客戶端&#xff08;瀏覽器&#xff09;發送的顯式的數…

第二篇 python基礎知識總結:數據、運算符

引子 我們跟任何人交流&#xff0c;說的每一句都是都一些文字組成&#xff0c;包含名詞、動詞、語句、標點符號等&#xff0c;組成我們說普通話構成的基本要素。同理我們學習python語言也要明白這些基本要素&#xff0c;也就是我們常說的基本語法&#xff0c;這是我們必須掌握的…

【BZOJ1797】[AHOI2009]最小割(網絡流)

【BZOJ1797】[AHOI2009]最小割&#xff08;網絡流&#xff09; 題面 BZOJ洛谷 題解 最小割的判定問題&#xff0c;這里就當做記結論吧。&#xff08;源自\(lun\)的課件&#xff09; 我們先跑一遍最小割&#xff0c;求出殘量網絡。然后把所有還有流量的邊拿出來跑\(Tarjan\)縮\(…

koa --- 使用Sequelize連接mysql

Sequelize介紹 為了快捷開發,社區出現了一系列的ORM(Object Relational Mapping)類庫ORM的字面意思為對象關系映射,它提供了概念性的、易于理解的模型化數據的方法。通過ORM,可以降低操作數據庫的成本。開發者不需要通過編寫SQL腳本來操作數據庫,直接通過訪問對象的方式來查詢…

Java Web Jsp

Java Web Jsp JSP全稱Java Server Pages&#xff0c;是一種動態網頁開發技術。它使用JSP標簽在HTML網頁中插入Java代碼。標簽通常以<%開頭以%>結束。 JSP是一種Java servlet&#xff0c;主要用于實現Java web應用程序的用戶界面部分。網頁開發者們通過結合HTML代碼、XHT…

Android gravity和layout_gravity的區別

一、gravity和layout_gravity相同處 兩者都是設置對齊方式的屬性。內部的屬性值相同。 根據英文意思也能理解其中的意思。如center_horizontal表示在水平方向上的位置為中間。 二、gravity和layout_gravity的不同處 gravity是設置自身內部元素的對齊方式。比如一個TextView&…

koa --- mongoose連接mongoDB

使用Mongoose對MongoDB進行操作 const mongoose require(mongoose); mongoose.connect(mongodb://localhost/test,{ })Mongoose中的Schema 定義Schema categorySchema const categorySchema new mongoose.Schema({name:String,description: String,createdAt:{type: Date,…

Java Web 請求轉發與請求重定向

Java Web 請求轉發與請求重定向 請求轉發 服務器行為&#xff0c;即用戶向服務器發送了一次http請求&#xff0c;該請求可能會經過多個信息資源處理以后菜返回給用戶&#xff0c;各個信息資源使用請求轉發機制互相轉發請求&#xff0c;但是用戶是感覺不到請求轉發的。通過req…