跨文件拆分时使用 router.use 表示路由器未定义参数 [英] Express Router undefined params with router.use when split across files

查看:16
本文介绍了跨文件拆分时使用 router.use 表示路由器未定义参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这是否是 Express 中的错误,或者我只是做错了什么(可能是后者),但我发现 req.params 仅在最后一步保留参数要求.为了证明我的意思:

I'm not sure if this is a bug in Express, or if I'm just doing something wrong (probably the latter), but I'm finding that req.params is only retaining parameters in the final step of the request. To demonstrate what I mean:

工作示例:

router.get('/:id/test', function(req, res){
    // req.params.id is not undefined
});

不起作用:(

文件 1:

router.use('/:id', require('./file2'));

文件 2:

router.get('/test', function(req, res){
    // req.params.id is undefined?!
});

现在...以上对我来说似乎完全不合逻辑,因为 Express 生成器以上述方式定义了路线 - 而且它仍然必须在某处的路径中定义.当然我应该仍然能够访问id"吗?

Now... the above seems totally illogical to me, seeing as the Express generator defines routes in the above way - and it must still be defined in the path somewhere. Surely I should still be able to access "id"?

所以基本上,我错过了什么吗?这是故意的/是否记录在案?FWIW 我正在使用 Express v4.12.0.

So basically, am I missing something? Is this deliberate/is it documented? FWIW I'm using Express v4.12.0.

免责声明:文件的事情可能无关紧要,但安全总比抱歉好.

Disclaimer: the file thing is probably irrelevant, but better to be safe than sorry.

推荐答案

当你在 File 2 中创建你的 Router 时,你需要告诉它从 parent 继承 params.

When you create your Router in File 2, you need to tell it to inherit params from parents.

var router = express.Router({mergeParams: true});

http://expressjs.com/api.html#router

这篇关于跨文件拆分时使用 router.use 表示路由器未定义参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆