0

I'm new to Node.js. I've pulled some code from examples, but somehow I've broken something :).

At this time, in my app.js file, I have a line that I think wires up Express with Node.js. That line looks like this:

app.js

var routes = require('./routes/index');
// ...
app.get('/', routes.router);

Then, in ./routes/index.js I have the following:

routes/index.js

var express = require('express');
var router = express.Router();

/* GET home page */
router.get('/', function(req, res) {
    res.send('respond with a resource');
});
module.exports = router;

When I run this, I get the following error:

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

I don't understand. What am I doing wrong?

Thanks!

JQuery Mobile
  • 6,221
  • 24
  • 81
  • 134

2 Answers2

2

app.js

var routes = require('./routes/index');
//var routes = require('./routes') --> this works 
// ...
app.use('/', routes); //Using the router instance as a middleware , relative to '/'

routes/index.js

var express = require('express');
var router = express.Router(); // new instance of Router

/* GET home page */
router.get('/', function(req, res) {
    res.send('respond with a resource');
});
module.exports = router; // You export the intance

UPDATE if you want more than 1 route file

app.js

var routes = require('./routes')
app
 .use("/user",routes.user)
 .use("/other",routes.other)

routes/index.js

module.exports = {
  user : require(./user),
  other : require(./other)
}

routes/user.js

var router = require("express").Router()

router.get("/",function (req,res){
  // GET /user
})
.post("/",function (req,res){
  //POST /user
})

module.exports = router;

routes/other.js

var router = require("express").Router()

router.get("/",function (req,res){
  // GET /other
})
.post("/",function (req,res){
  //POST /other
})

module.exports = router;
cshion
  • 1,173
  • 1
  • 10
  • 19
  • Is it possible to have two route files? For example `routes/users.js` and `routes/orders.js`? The routes in the `users.js` file would have routes that start with `/users` and the routes in `orders.js` would have routes that start with `/users/{userId}/orders`. Is that possible? – JQuery Mobile Sep 05 '15 at 12:53
  • of course , thats a good idea , you could get different routes , going to edit my answer. – cshion Sep 05 '15 at 16:58
0

An example of a basic server.js:

var express = require('express');
var app = express();

app.get('/', function(req, res) {
    res.sendfile(__dirname + '/client/views/index.html');
});

app.listen(3000, function() {
    console.log('Server running on localhost:3000');
});

Comparing, I believe you need to listen to the port. Also I think your res.send should be sending an actual file.

More documentation on Nodejs here: https://nodejs.org/api/

Also found a related questions on SO: Node Route.get() requires callback function but got a [object undefined]

Community
  • 1
  • 1
eSs
  • 59
  • 8