Koa 是現在最流行的基於Node.js平臺的web開發框架,由 Express 原班人馬打造
,利用 async 函數,Koa丟棄了回調函數,並有力地增強錯誤處理。 Koa 並沒有
捆綁任何中間件,給人一種乾淨利落的感覺,體積小、編程方式乾淨
1. 安裝
npm install koa --save
cnpm i koa-router --save
2. 使用
let Koa = require('koa')
let app = new Koa();
//1.使用koa路由的時候,需要安裝對應的路由koa-router
// cnpm i koa-router --save
//2.引入路由
let Router = require('koa-router');
let router = new Router();
// ctx 上下文 ;包含了request和response 的等信息;
//3.規劃路由
router.get("/", async(ctx) => {
ctx.body = '首頁面'
});
router.get("/news", async(ctx) => {
ctx.body = '新聞頁面'
});
router.get("/product", async(ctx) => {
ctx.body = '產品頁面'
});
//4.啓用路由
app.use(router.routes()) /*啓動路由*/
app.use(router.allowedMethods()); /* 可配可不配置,建議配置 */
app.listen(3002)
3. 獲取查詢參數
router.get("/", async(ctx) => {
ctx.body = '首頁面'
console.log(ctx.query)
// 請求地址
console.log( ctx.request.url )
// 請求查詢參數
console.log( ctx.request.query )
});
[Object: null prototype] { name: ‘doudou’ }
/?name=doudou
[Object: null prototype] { name: ‘doudou’ }
4. 動態路由
二級動態路由
router.get("/news/:name", async(ctx) => {
ctx.body = '新聞頁面'
console.log(ctx.params.name)
});
三級動態路由
router.get("/news/:name/:age", async(ctx) => {
ctx.body = '新聞頁面' + ctx.params.name + ctx.params.age
});