[英]Express js get parameters from root of URL (Not as simple as req.params)
I've made an api and I've routed it as follows:我制作了一个 api,并按如下方式对其进行了路由:
In the main routes file:在主路由文件中:
//with sub-route
app.use('/api/test/:test', require('./api/test'));
//Without sub-route
app.use('/api/test2/:test', function(req, res){
console.log('in test', req.params, req.body);
return res.status(200).json({params: req.params, body: req.body});
});
Accessing the second route displays the :test in req.params, as expected.访问第二条路由会按预期显示 req.params 中的 :test 。
In the modular routes folder ('./api/test') I have a sub-router (index.js) which looks like this:在模块化路由文件夹 ('./api/test') 中,我有一个子路由器 (index.js),如下所示:
router.get('/:test2', controller.getItem);
with a handler:带处理程序:
exports.getItem = function getItem(req, res) {
console.log('in getItem \nreq.params', req.params, '\nreq.body: ', req.body);
return res.status(200).json({yes: 'yes', params: req.params, body: req.body});
};
So the first url , which has no sub-routing is: /api/test2/:test and logs out whatever you put in place of :test in req.params.所以第一个没有子路由的url是: /api/test2/:test并注销你在 req.params 中放置的任何 :test 。
The second url , which has sub-routing is: /api/test/:test/:test2 , but when you send your get request only :test2 appears in req.params .第二个具有子路由的url是: /api/test/:test/:test2 ,但是当您发送 get 请求时,只有 :test2 出现在 req.params 中。
It seems that if you use this pattern any variables in the 'root' of the route (ie in the primary router) are not picked up.似乎如果您使用此模式,则不会选择路由的“根”(即主路由器中)中的任何变量。
Is there a way to fix this?有没有办法来解决这个问题?
Thanks谢谢
You will need a middleware to fix this for you:您将需要一个中间件来为您解决这个问题:
function paramFix(req, res, next) {
req._params = req.params;
next();
}
app.use('/api/test/:test', paramFix, require('./api/test'));
And then use req._params.test
in your last callback function.然后在最后一个回调函数中使用req._params.test
。
So reflect multiple levels of mounting you can extend your middleware like this:因此,反映多个级别的安装,您可以像这样扩展您的中间件:
function paramFix(req, res, next) {
req._params = req._params || {};
for (var key in req.params) {
if (req.params.hasOwnProperty(key)) {
req._params[key] = req.params[key];
}
}
next();
}
app.use('/api/test/:test', paramFix, require('./api/test'));
express.js (>= v4.5.0+) provides a direct solution without having to implement middleware. express.js (>= v4.5.0+) 提供直接解决方案,无需实现中间件。 https://expressjs.com/en/api.html#express.router https://expressjs.com/en/api.html#express.router
While creating the router, pass the mergeParams
flag.在创建路由器时,传递mergeParams
标志。
var router = express.Router({ mergeParams: true })
mergeParams
preserves the req.params values from the parent router. mergeParams
保留来自父路由器的 req.params 值。 If the parent and the child have conflicting param names, the child's value takes precedence.如果父级和子级具有冲突的参数名称,则子级的值优先。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.