2016-01-26 113 views
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 

回答

1

啊,我需要學習閱讀。我解釋了koa-router文檔說router.redirect()打算在HTTP動詞功能中使用。

正確的使用率低於:

//either this 

router.redirect('/route1', '/route2'); 

//or regular koa redirect 

router.all('/route1', function *() { 
    this.redirect('/route2'); 
});