koa-router使用指南

koa-router文檔地址 https://www.npmjs.com/package/koa-router

安裝koa                   cnpm install koa --save 

安裝koa-router         cnpm install koa-router --save

使用koa-router :

  1. 路由導(dǎo)航

  2. get請求獲取參數(shù) (ctx.query)

  3. 動態(tài)路由及其獲取參數(shù)(/product/:id ctx.params.id)

//引入 koa模塊
 
var Koa=require('koa');
 
var router = require('koa-router')();  /*引入是實例化路由** 推薦*/
 
//實例化
var app=new Koa();
 
router.get('/',async (ctx)=>{
    ctx.body="首頁";
 
})
 
 
app.use(router.routes());   /*啟動路由*/
app.use(router.allowedMethods());
/*
 * router.allowedMethods()作用: 這是官方文檔的推薦用法,我們可以
 * 看到 router.allowedMethods()用在了路由匹配 router.routes()之后,所以在當(dāng)所有
 * 路由中間件最后調(diào)用.此時根據(jù) ctx.status 設(shè)置 response 響應(yīng)頭 
 *
 */
app.listen(3000);


get請求獲取參數(shù)

/*在 koa2 中 GET 傳值通過 request 接收,但是接收的方法有兩種:query 和 querystring。
     query:返回的是格式化好的參數(shù)對象。
     querystring:返回的是請求字符串。*/
 
//獲取get傳值
//http://localhost:3000/newscontent?aid=123
 
router.get('/newscontent',async (ctx)=>{
 
    //從ctx中讀取get傳值
 
    console.log(ctx.query);  //{ aid: '123' }       獲取的是對象   用的最多的方式  **推薦
    console.log(ctx.querystring);  //aid=123&name=zhangsan      獲取的是一個字符串
    console.log(ctx.url);   //獲取url地址
 
    //ctx里面的request里面獲取get傳值
 
    console.log(ctx.request.url);
    console.log(ctx.request.query);   //{ aid: '123', name: 'zhangsan' }  對象
    console.log(ctx.request.querystring);   //aid=123&name=zhangsan
 
})

動態(tài)路由

//請求方式 http://域名/product/123
router.get('/product/:aid',async (ctx)=>{
    console.log(ctx.params); //{ aid: '123' } //獲取動態(tài)路由的數(shù)據(jù)
    ctx.body='這是商品頁面';
});

ps:存檔

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容