问题描述
我不确定这是否是 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
时,你需要告诉它从父母那里继承 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 的 Express Router 未定义参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!