简体   繁体   中英

Redirecting with nested routes in koa with koa-router

How do I do redirects with nested routes using koa-router ?

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";
});

The above code results in the following error at runtime when navigating to /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

Ah, I need to learn to read. I interpretted the koa-router docs to say router.redirect() was intended to be used within an HTTP verb function.

The correct usage is below:

//either this

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

//or regular koa redirect

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM