简体   繁体   English

express / node.js-如何将路由参数传递给其他文件?

[英]express/node.js - How to pass route parameters to other files?

Encountered a strange bug where if I have a route defined like so in routes/posts/index.js: 遇到一个奇怪的错误,如果我在route / posts / index.js中定义了这样的路由:

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

Inside ./edit, I have the endpoint defined like so: 在./edit内部,我定义了端点,如下所示:

router.post('/', passport.authenticate('jwt', { session: false}), function(req, res){

If I hit /posts/:id/edit, I successfully hit the endpoint in ./edit, but const id = req.params.id; 如果我命中了/ posts /:id / edit,我就成功命中了./edit中的端点,但是const id = req.params.id; will be undefined. 将是不确定的。 However, if I define the route directly in routes/posts/index.js, req.params.id will be defined. 但是,如果我直接在route / posts / index.js中定义路由,则将定义req.params.id

What is the correct way for letting the route in ./edit 'recognize' the id parameter? 让./edit中的路由“识别” id参数的正确方法是什么?

您可以通过将{mergeParams: true}传递给express.Router()来合并父路由器参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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