gpt4 book ai didi

node.js - 使用 koa-router 在 koa 中使用嵌套路由进行重定向

转载 作者:太空宇宙 更新时间:2023-11-04 00:45:14 28 4
gpt4 key购买 nike

如何使用 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";
});

导航到 /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

最佳答案

啊,我要学会读书。我将 koa-router 文档解释为 router.redirect() 旨在在 HTTP 动词函数中使用。

正确的用法如下:

//either this

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

//or regular koa redirect

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

关于node.js - 使用 koa-router 在 koa 中使用嵌套路由进行重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35006264/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com