简体   繁体   中英

Pass route parameter to controller in ExpressJS

I'm using passport JS to authenticate my user account. Passing the passport variable from app.js to routes.js and controller.js. When I pass between routes.js and controller.js, I have no idea how to implement. I tried different approaches but didn't work. My first priority was stored all the implementation codes inside controller instead of routes.

App.js

var userRouter = require('./api/routes/userRoutes.js')(app,passport);

Routes.js

module.exports = function(app,passport){
  var UserRouter = express.Router();
  users = require('./../controllers/UserController')
  UserRouter.post('/users', users.authenticate);
}

Controller.js

exports.authenticate = function(req, res, next){
    // How do I get passport variable here?
}

Not sure that it is the best way in this case, but like an option you can try this:

In App.js:

global. passport = passport;
var userRouter = require('./api/routes/userRoutes.js')(app, passport);

In Controller.js:

exports.authenticate = function(req, res, next) {
    console.log(global.passport);
}

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