Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

javascript - 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");
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...