Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express routes: .get() requires callback functions but got a [object Object]

Ok, this should be easy for somebody to point out.

I checked the other similar questions and none helped.

I'm trying to move all my routes to a separate routes.js file. In it I have:

module.exports = function (app) {

  var user = {
      list : require('./routes/user.js')
    } 
  , index = {
      index : require('./routes/index.js')
    } 


  app.get('/', function(request, response){
    response.send('You made it to the home page.')
  });

  app.get('/users', user.list);
}

And in my app.js file I have this:

var register_routes = require('./routes.js')
register_routes(app)

My index route works fine, but it kicks back on app.get('/users', user.list); with this error:

.get() requires callback functions but got a [object Object]

This is an out of the box express app so theres not too much to describe.

Thanks.

EDIT: Per request, here is what is in ./routes/user.js :

exports.list = function(req, res){
  res.send("respond with a resource");
};
like image 270
JDillon522 Avatar asked Sep 10 '25 20:09

JDillon522


1 Answers

You export an object with the key list having the your function as value.

So to access your function you would need to do this require('./routes/user.js').list

Or with your code user.list.list.

To solve this you have two possibilities.

Either write:

var user = {
  list : require('./routes/user.js').list
}

Or:

module.exports = function(req, res){
   res.send("respond with a resource");
};

EDIT

If your routes/user.js will probably later look like this:

module.exports.list = function(req, res){
   res.send("respond with a resource");
};

module.exports.delete = function(req, res){
   res.send("delete user");
};

If yes then you can just write it that way in your routes.js:

var user = require('./routes/user.js');
like image 172
t.niese Avatar answered Sep 12 '25 10:09

t.niese