node js - get url params from original base url

本小妞迷上赌 提交于 2021-01-29 09:07:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!