Nodejs, Express, routes

时间:2017-12-18 06:14:47

标签: node.js express routes

I have build an api using express. In my routes file I have:

app.route('/getBalances')
        .post(api.getBalances);

api.getBalances, depending on a parameter send through post called "vehicle" gets first which is the correct controller to load and to invoke its getBalances method, in example:

var controller = commonModel.getController(query.vehicle.toLowerCase());
controller.getBalances();

getBalances is not the only entry point I have, so I was wondering if it was possible to call a "global" method which is call for every entry point, in that way I wouldn't need to identify the correct controller on each method but on the global method.

Thanks in advance for your help.

1 个答案:

答案 0 :(得分:2)

使用在添加任何api路由之前运行的初步中间件。例如:

// This middleware has to be added first.
app.use(function(req, res, next) {

  var query = req.query; // or `req.body`, whatever you like
  if (query && query.vehicle) {
    req.controller = commonModel.getController(query.vehicle.toLowerCase());
  }

  next(); // delegate request to the next routes

});

// Now add specific api middlewares.
app.route('/getBalances')
  .post(function(req, res) {

    var controller = req.controller; // we've populated this earlier
    res.send(controller.getBalances());

  });

app.route('/anotherMethod')
  .post(function(req, res) {

    var controller = req.controller;
    // etc.

  });