简体   繁体   中英

Express: Getting full route parameters

I'm building a node.js application using express framework. The app routes are defined in separate files, so basically I have one router per resource. Here's an example:

app.js

var fooRoutes = require('./fooRoutes.js');
...
router.use('/users/:id/foos',fooRoutes);

fooRoutes.js

var fooController = require('./../controllers/fooController.js');
router.get('/', function(req, res) {
  fooController.getFoos(req, res);
});

fooController.js

var FooController = function() {
  this.getFoos = function(req, res) {
    var foos = [];
    fooService.findFoosByUser(req.params.id, function(err, recordset) {
      if (err) {
        res.send(400, err);
      }
      res.send(200, recordset);
    });
  };
};

The problem is that I cannot get the id parameter from fooController. If I try to log it from the app file, I can get it. I guess it's because the route at that point recognizes it as a parameter.

Is there a way to get that parameter from fooController ?

I've found that express added a feature to merge parameters from parent routers. This can be found here

With this, I can solve it by declaring my router like this:

var router = express.Router({mergeParams: true});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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