上一節文末參考的文章我們可以了解到:
-
在
koa
實例化之后,我們會使用use
來加載中間件; -
每一個中間件都是一個函數,函數的參數分別是
ctx
和next
; -
建立好http服務器之后,
koa-compose
會將中間件存放在一個數組中,並依次從數組中執行每一個函數; -
每一個中間函數會調用next方法去取下一個中間件函數繼續執行,且每一個中間件都會返回一個
promise
對象。
認識Koa-Router
此時我們無論在瀏覽器輸入什么路徑,打印的都是一樣的內容,因為使用的是同一個中間件。
http://localhost:3000/login
http://localhost:3000/book/get
http://localhost:3000/book/edit
...
修改以下代碼:
const Koa = require('koa'); const app = new Koa(); app.use(async (ctx,next)=>{ if(ctx.path === '/'){ console.log("主頁"); }else if(ctx.path === '/book/edit'){ console.log("編輯書本"); } await next(); }); app.listen(3000);
當訪問http://localhost:3000
時打印的是“主頁”;
當訪問http://localhost:3000/book/edit
時打印的是“編輯書本”。
如果沒寫一個api都要這樣判斷的話代碼會很冗余也很維護,此時我們就需要koa-router
了。
cnpm i koa-router --save const Koa = require('koa'); const Router = require('koa-router'); const app = new Koa(); const router = new Router(); router.get("/",(ctx,next)=>{ console.log("主頁"); }); router.get("/book/edit",(ctx,next)=>{ console.log("編輯書本"); }); // router注冊到app app.use(router.routes()); app.listen(3000);
學會使用postman
最近在做商品小程序,所以准備自給自足自己開發一套api,所以此次開發的接口跟商城有關。
在postman中新建一個collection
取名為mall
,在mall
文件夾下新增名字為【首頁】、【我的】、【購物車】等文件夾。(有些人喜歡用類別區分文件夾名字,我不是專業的,用頁面區分文件夾名字)。在【首頁】文件夾下新增三個requeset
。
修改代碼:
使用postman請求
加上API的前綴
也許你的接口開發是針對多個項目的,比如我同時一起開發mall
和admin
兩種接口,mall
接口應該都用mall
開頭,admin
都應該用admin
開頭。
修改代碼為:
const router = new Router({prefix:'/mall'});
此時請求應該為:
http://localhost:3000/mall/banners
學會獲得參數
路由中冒號后面的參數
router.get("/banners/:id",(ctx,next)=>{ const params = ctx.params; ctx.body = params; });
訪問 http://localhost:3000/mall/banners/1
路由中問號后面的參數
router.get("/banners",(ctx,next)=>{ const query = ctx.query; ctx.body = query; });
訪問 http://localhost:3000/mall/banners?id=2
路由中header帶有的參數
router.get("/banners",(ctx,next)=>{ const header = ctx.header; ctx.body = header; });
訪問 http://localhost:3000/mall/banners
並在postman的header
中添加id=3
當請求方法是POST時獲得body中的參數
cnpm i koa-bodyparser --save
const Koa = require('koa'); const Router = require('koa-router'); const bodyparser = require("koa-bodyparser"); const app = new Koa(); const router = new Router({prefix:'/mall'}); app.use(bodyparser ()); router.post("/banners",(ctx,next)=>{ const res = ctx.request.body; ctx.body = res; }); // router注冊到app app.use(router.routes()); app.listen(3000);
如果使用form-data的話會獲取不到參數,需要使用koa-multer
,后期有圖片上傳的接口的時候我們再研究。
之前使用 koa2 的時候,處理 post 請求使用的是
koa-bodyparser
,同時如果是圖片上傳使用的是koa-multer
。這兩者的組合沒什么問題,不過
koa-multer
和koa-route
(注意不是koa-router
) 存在不兼容的問題。
看到網上這段話,后期應該會使用koa-body