koa-router文檔地址 https://www.npmjs.com/package/koa-router
安裝koa cnpm install koa --save
安裝koa-router cnpm install koa-router --save
使用koa-router :
路由導(dǎo)航
get請求獲取參數(shù) (ctx.query)
動態(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:存檔