koa-router簡單使用

目錄

koa-router 實現路由


const Koa = require('koa');
/**
 * 調用方式
 * */
const Router = require('koa-router')();
const App = new Koa();

Router.get('/',(ctx,next)=>{
    ctx.body = 'Hello koa';
})

Router.get('/news',(ctx,next)=>{
    ctx.body = '新聞App'
})
/**
 * 啓動路由
 * */
App.use(Router.routes());
/**
 * 我們可以看到router.allowedMethods()用在了路由匹配router.routes()之後,
 * 所以在當所有路由中間件最後調用.此時根據ctx.status設置response響應頭
 * */
App.use(Router.allowedMethods());

App.listen(3000,()=>{
    console.log('quick start at port 3000')
})

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章