Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

like image 786
user1071182 Avatar asked Apr 14 '13 03:04

user1071182


1 Answers

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);
    };
};
like image 152
loganfsmyth Avatar answered Sep 19 '22 18:09

loganfsmyth