一笨鸡、Koa 路由
1.安裝koa-router
cnpm install koa-router -S
2.一個(gè)簡(jiǎn)單的路由實(shí)例
const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()
//配置路由
router.get("/", async (ctx)=>{
ctx.body = "<h1>首頁(yè)</h1>"
}).get("/news", async (ctx)=>{
ctx.body = "<h1>新聞頁(yè)</h1>"
})
//啟動(dòng)路由
app.use(router.routes());
app.use(router.allowedMethods()); //可以配置也可以不配置
/* 作用: 這是官方文檔的推薦用法,我們可以看到 router.allowedMethods()用在了路由匹配 router.routes()之后,
所以在當(dāng)所有路由中間件最后調(diào)用.此時(shí)根據(jù) ctx.status 設(shè)置 response 響應(yīng)頭*/
app.listen(3000)
3.另一種推薦的寫法
const Koa = require('koa')
const router = require('koa-router')()//引入并實(shí)例化路由
const app = new Koa
router.get('/',async (ctx) => {
ctx.body = "<h1>首頁(yè)</h1>"
})
router.get('/news',async (ctx) => {
ctx.body = "<h1>新聞</h1>"
})
router.get('/products',async (ctx) => {
ctx.body = "<h1>產(chǎn)品</h1>"
})
//啟動(dòng)路由
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000)
二、Koa 路由 get 傳值
在 koa2 中 GET 傳值通過 request 接收锡足,但是接收的方法有兩種:query 和 querystring。
query:返回的是格式化好的參數(shù)對(duì)象。
querystring:返回的是請(qǐng)求字符串末秃。
//獲取get傳值
router.get('/news',async (ctx) => {
//1.從ctx中讀取傳值
//訪問:http://localhost:3000/news?id=2&catid=12
console.log(ctx.query);//用的最多的方式 (推薦)
//輸出{ id: '2', catid: '12' }
console.log(ctx.querystring);
//id=2&catid=12
console.log(ctx.url);
///news?id=2&catid=12
//2.從ctx里的request
console.log(ctx.request);
//{method,url,header}
console.log(ctx.request.query);
//{ id: '2', catid: '12' }
console.log(ctx.request.querystring);
//id=2&catid=12
ctx.body = "<h1>新聞</h1>"
})
三陡叠、Koa 動(dòng)態(tài)路由
這里有點(diǎn)類似于vue里的路由
//動(dòng)態(tài)路由 加?表示后面可以不加參數(shù) 當(dāng)然也支持多個(gè)參數(shù)
router.get('/news/:aid?',async (ctx) => {
//獲取動(dòng)態(tài)路由的傳值
//http://localhost:3000/news/lqs
console.log(ctx.params)
//{ aid: 'lqs' }
ctx.body = "<h1>新聞</h1>"
})