问题
In my node JS express app I have defined routes with path having regex expressions in my app.js file. i.e
var tableRoute = require('./routes/tables');
app.use('/keyspaces/(regex to match param)/tables',tableRoute);
Then in my routes/tables.js file I have following handler defined for this route
router.get('/', function(req, res, next) {
// need to access url param here
});
Now clearly I cannot access my url param via req.params.xzy because here handler is defined for '/' not for '/keyspaces/:xzy/tables', is there any way I can access this url param here from original base url.
回答1:
You can add a middleware to handle it. In your example :
var tableRoute = require('./routes/tables');
app.use('/keyspaces/:xzy/tables',function(req,res,next){
req.xyz=req.params.xyz;
next();
},tableRoute);
Then in routes table you can access it and set req.params by your own :
router.get('/', function(req, res, next) {
req.params.xyz = req.xyz;
});
回答2:
refer to this comment.
for me its work only with call to the next middleware, else he will end in the first middleware call
like this:
var tableRoute = require('./routes/tables');
app.use('/keyspaces/:xzy/tables',function(req,res,next){
req.xyz=req.params.xyz;
next();
},tableRoute);
and then you can add:
router.get('/', function(req, res, next) {
req.params.xyz = req.xyz;
});
来源:https://stackoverflow.com/questions/28612822/node-js-get-url-params-from-original-base-url