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并注销你放置的任何东西:test in req.params。
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
1 个解决方案
#1
2
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'));
#1
2
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'));