Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Route.get() requires callback functions but got a "object Undefined"

I am learning making Todo app. On the website, I am studying is https://coderwall.com/p/4gzjqw/build-a-javascript-todo-app-with-express-jade-and-mongodb

I typed as instruction describes,

app.js

var main = require('./routes/main'); var todo = require('./routes/todo'); var todoRouter = express.Router(); app.use('/todos', todoRouter); app.get('/', main.index); todoRouter.get('/',todo.all); todoRouter.post('/create', todo.create); todoRouter.post('/destroy/:id', todo.destroy); todoRouter.post('/edit/:id', todo.edit); 

/routes/todo.js

module.exports ={   all: function(req, res){     res.send('All todos');   },   viewOne: function(req, res){     console.log('Viewing '+req.params.id);   },   create: function(req, res){     console.log('Todo created');   },   destroy: function(req, res){     console.log('Todo deleted');   },   edit: function(req, res){     console.log('Todo '+req.params.id+' updated');   } }; 

and I got this error message

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

Did I miss something here?

like image 945
jayko03 Avatar asked Apr 11 '16 20:04

jayko03


2 Answers

In the tutorial the todo.all returns a callback object. This is required for the router.get syntax.

From the documentation:

router.METHOD(path, [callback, ...] callback)

The router.METHOD() methods provide the routing functionality in Express, where METHOD is one of the HTTP methods, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are router.get(), router.post(), router.put(), and so on.

You still need to define the array of callback objects in your todo files so you can access the proper callback object for your router.

You can see from your tutorial that todo.js contains the array of callback objects (this is what you are accessing when you write todo.all):

module.exports = {     all: function(req, res){         res.send('All todos')     },     viewOne: function(req, res){         console.log('Viewing ' + req.params.id);     },     create: function(req, res){         console.log('Todo created')     },     destroy: function(req, res){         console.log('Todo deleted')     },     edit: function(req, res){         console.log('Todo ' + req.params.id + ' updated')     } }; 
like image 146
roflmyeggo Avatar answered Oct 03 '22 18:10

roflmyeggo


I got the same error. After debugging, I found that I misspelled the method name that I imported from the controller into the route file. Please check the method name.

like image 27
DiaMaBo Avatar answered Oct 03 '22 20:10

DiaMaBo