简体   繁体   中英

Express : Calling functions on app.param in multiple routes with same para name

I have 2 routes defined in 2 separate files but a parameter RecordId is same for both the routes:

I am expecting that : 1) whenever I call /api/CountryMaster/:RecordId , only RecordByIdCtry function should be called. &

2) when I am calling /api/commonMaster/:MasterName/:RecordId , only RecordByIdCmn function should be called.

However, both functions are getting called with the order being as set in javascript. ie

 require('../app/routes/commonMaster.server.routes.js')(app);
    require('../app/routes/countryMaster.server.routes.js')(app);

How can i stop these & ensure that only one method is called.

//CountryMaster.js

var ctrl = require('../../app/controllers/CountryMaster.server.ctrl.js');
var users = require('../../app/controllers/user.server.ctrl.js');
module.exports = function (app)
{

    app.route('/api/CountryMaster')
    .get(users.requiresLogin,ctrl.list) 
    .post(users.requiresLogin,ctrl.create);


     app.route('/api/CountryMaster/:RecordId')
    .get(ctrl.read)
    .put(users.requiresLogin, ctrl.hasAuthorization, ctrl.update)
    .delete(users.requiresLogin, ctrl.hasAuthorization, ctrl.delete);

    app.param('RecordId', ctrl.RecordByIdCtry);
}

//CommonMaster.js

var ctrl = require('../../app/controllers/commonMaster.server.ctrl.js');
var users = require('../../app/controllers/user.server.ctrl.js');
module.exports = function (app)
{
    app.route('/api/commonMaster/:MasterName')
    .get(users.requiresLogin,ctrl.list) 
    .post(users.requiresLogin,ctrl.create);
    app.route('/api/commonMaster/:MasterName/:RecordId')
    .get(ctrl.read)
    .put(users.requiresLogin, ctrl.hasAuthorization, ctrl.update)
        .delete(users.requiresLogin, ctrl.hasAuthorization, ctrl.delete);
    app.param('MasterName', ctrl.MasterName);
    app.param('RecordId', ctrl.RecordByIdCmn);
}

How can I ensure that only one method is called..

In your code, app is always the same app, so you're basically declaring two handlers for the same parameter, which isn't going to work.

You should use entirely separate routers instead:

// CountryMaster.js
...
module.exports = function(app) {
  var router = require('express').Router();

  router.route('/')
        .get(...)
        .post(...);

  router.route('/:RecordId')
        .get(...)
        .put(...)
        .delete(...);

  // The magic:
  router.param('RecordId', ctrl.RecordByIdCtry);

  // Mount the router on `/api/CountryMaster`
  app.use('/api/CountryMaster', router);
};

And similar for CommonMaster.js .

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