剛剛開始學習Koa框架不久,在使用koa-router路由中間件的時候遇到一個坑,浪費了點時間,必須要做個記錄,給後人一個提醒!
koa-router簡單使用方式如下:
app.js
const koa = require('koa');
const router = require('koa-router')();
const http = require('http');
const app = koa();
router.get('/',function* (){
//do something!
})
app.use(indexRouter.routes(),indexRouter.allowedMethods());
http.createServer(app.callback()).listen(3000,function(){'the server is listening on port 3000'})
考慮後期開發路由的增多,於是把所有路由規則放在另一個文件裏,再在app.js裏導入
新增routes/index.js
const router = require('koa-router')();
router.get('/',function*(){
console.log("the request path is '/' ");
//do something else!
});
router.get('/ha',function*(){
console.log('path is /ha');
});
module.exports = router;
app.js修改如下:
const koa = require('koa');
const router = require('koa-router')();
const http = require('http');
const indexRouter = require('./routes/index');
const app = koa();
router.use('/',indexRouter.routes(),indexRouter.allowedMethods());
app.use(indexRouter.routes(),indexRouter.allowedMethods());
http.createServer(app.callback()).listen(3000,function(){'the server is listening on port 3000'})
瀏覽器訪問如下路徑:
http://127.0.0.1:3000/ -----可以正常訪問
http://127.0.0.1:3000/ha -----無法訪問
閱讀koa-router文檔發現有Nested Router(嵌套路由)這一說,其原理就是將多個路徑合併起來,而我代碼裏寫的路由配置,轉換過來的話,其實路由是這樣的:
http://127.0.0.1:3000/
http://127.0.0.1:3000//ha ----這種肯定無法訪問
將index.js文件 router.get('/ha')路徑修改成router.get('ha')即可。路由顯示爲
http://127.0.0.1:3000/ha
並且可以正常訪問地址
剛接觸koa不久,本文有誤之處,還請提出,感謝!