刚刚开始学习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不久,本文有误之处,还请提出,感谢!