Express路由器未定义的参数与router.use分割时跨文件 [英] Express Router undefined params with router.use when split across files

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

问题描述

我不知道这是否是Express中的错误,或者如果我只是做错了(可能是后者),但是我发现req.params只是在最后一步中保留参数请求。为了表明我的意思:



工作示例

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

不工作:(



文件1:

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

文件2:

  router.get('/ test',function(req,res){
// req.params。 id是未定义的?
});

现在...以上看起来完全不合逻辑对我来说,看到Express生成器以上述方式定义了路由,而且还必须在某处的路径中定义,当然我还是可以访问id?



免责声明:

所以基本上,我错过了什么吗?这是有意的/是否记录在案?FWIW我正在使用Express v4.12.0。 / strong>文件的事情可能是无关紧要的,但比最好的安全更好。

解决方案

创建你的路由器文件2 中,您需要告诉它从父母继承参数。

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

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


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:

Working Example:

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

Doesn't Work :(

File 1:

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

File 2:

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

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"?

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.

解决方案

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

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

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