user1071182
user1071182

Reputation: 1627

Node.js pass variable to route

I have very simple node.js noob question. How do I pass a variable to an exported route function?

Routes file

exports.gettop = function(n, req, res) {
  console.log(n);
  res.send(200);
};

Server file

app.get('/api/v1/top100', routes.gettop(100)); 

Error: .get() requires callback functions but got a [object Undefined]

Upvotes: 16

Views: 28805

Answers (4)

Ronald Coarite
Ronald Coarite

Reputation: 4746

Try

app.post('/find_user',
   require('./naas/autentication'),
   require('./naas/authorization')(paramForRouter),
   require('./routes/users'));

Where

require('./naas/autentication') is for example

module.exports = function (req, res, next) {next();}

And require('./naas/authorization')(paramForRouter) is

module.exports = function (paramForRouter) {
    return function (req, res, next) {
        this.param = paramForRouter;
        console.log("Param value",this.param);
        next();
    };
};

Upvotes: 3

saintedlama
saintedlama

Reputation: 6898

As your code looks like you're using express you can use express app locals and express result locals to pass variables to your route. While the other answers propose working solutions I think that it's less obtrusive to use express mechanisms to set these variables.

With response locals (See Express API reference) you first have to set a variable somewhere in a middleware or route. I'll show the middleware approach

app.use(function(req,res, next) {
  res.locals.top = 200;
  next();
});

then in your route you can access this property via res.locals.variablename

exports.gettop = function(req, res) {
  console.log(res.locals.top);
  res.send(200);
};

In case you want to make these settings application wide a better approach is to use app locals (See Express API reference)

To set an app locals variable you can use

app.locals.top = 100;

To access this variable from your route use

exports.gettop = function(req, res){
  console.log(req.app.locals.top);
  res.send(200);
};

Upvotes: 18

robertklep
robertklep

Reputation: 203534

As an alternative to loganfsmyth's (very valid!) solution, you could leave your gettop function as-is and create a partial function:

app.get('/api/v1/top100', routes.gettop.bind(null, 100)); 

Upvotes: 7

loganfsmyth
loganfsmyth

Reputation: 161617

For your example, you want to create a new function that will close around your value of n. In your case, you are executing gettop and passing the returned value to express as your route, which means gettop needs to return the route handler.

exports.gettop = function(n){
    return function(req, res) {
        console.log(n);
        res.send(200);
    };
};

Upvotes: 31

Related Questions