1
如何使用koa-router
做嵌套路由重定向?用koa路由器在koa中嵌套路由重定向
app.js:
var router = require('koa-router')();
var route1 = require('./routes/route1');
var route2 = require('./routes/route2');
router.use('/route1', route1);
router.use('/route2', route2);
app.use(router.routes());
route1.js:
var router = require('koa-router')();
router.all('/', function *() {
router.redirect('/route2');
});
module.exports = router.routes();
route2.js:
導航到時var router = require('koa-router')();
router.all('/', function *() {
this.body = "route2";
});
上面的代碼導致以下運行時錯誤/route1
:
TypeError: Cannot read property '0' of undefined
at Router.redirect (/Users/colevarner/fullpower/node/motionxlive-koa/node_modules/koa-router/lib/router.js:477:18)
at Object.<anonymous> (/Users/colevarner/fullpower/node/motionxlive-koa/routes/support.js:54:12)
at next (native)
at onFulfilled (/Users/colevarner/fullpower/node/motionxlive-koa/node_modules/co/index.js:65:19)
at /Users/colevarner/fullpower/node/motionxlive-koa/node_modules/co/index.js:54:5
at Object.co (/Users/colevarner/fullpower/node/motionxlive-koa/node_modules/co/index.js:50:10)
at Object.toPromise (/Users/colevarner/fullpower/node/motionxlive-koa/node_modules/co/index.js:118:63)
at next (/Users/colevarner/fullpower/node/motionxlive-koa/node_modules/co/index.js:99:29)
at onFulfilled (/Users/colevarner/fullpower/node/motionxlive-koa/node_modules/co/index.js:69:7)
at /Users/colevarner/fullpower/node/motionxlive-koa/node_modules/co/index.js:54:5