max li
max li

Reputation: 2467

Send variables to router in ExpressJS

In my app.js, I have some variable like

var user = "max";

and a route function

app.post('/register', user.postRegister);

and in my /routes/user.js I have a module function like this

exports.postRegister = function(req, res){
   // how do get the user variable from here?
}

Upvotes: 2

Views: 760

Answers (3)

Sriharsha
Sriharsha

Reputation: 2443

I am thinking you are want to access the user information in the controllers, if that's the case. Its better to use sessions in this case.

Example:

var setSession = function(req, res, next)
{
  req.session.user = "max";
  //Or get the actual user by querying the database
  next();
}

then

app.post('/register', setSession, user.postRegister(user));

exports.postRegister = function(req, res){
   var user = req.session.user;
}

Upvotes: 0

robertklep
robertklep

Reputation: 203534

Create a partial function so the username will be passed as first argument to your handler:

// app.js
var userName = 'max';
app.post('/register', user.postRegister.bind(user, userName));

// routes/user.js
exports.postRegister = function(userName, req, res) {
  ...
}

Upvotes: 0

Alberto Zaccagni
Alberto Zaccagni

Reputation: 31580

You could do it with a closure, like so:

app.post('/register', user.postRegister(user));

exports.postRegister = function(user) {
  return function(req, res){
    // now you have user here
  }
}

Upvotes: 5

Related Questions