3

I'm new to Express. The way I'm doing my routing is kicking back an error.

Here is my relevant code:

app.js

var express = require('express')
  , routes = require('./routes')
  , http = require('http')
  , path = require('path')
  , firebase = require('firebase');

...

// Routing
app.get('/', routes.index);
app.get('/play', routes.play);

index.js and play.js

exports.index = function(req, res){
  res.sendfile('views/index.html');
};

exports.play = function(req, res){
  res.sendfile('views/play.html');
};

This is the error:

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

It references this line in app.js

app.get('/play', routes.play);

I'm lost as to why this doesnt work because the code structure is identical for routing to my index page and the index page loads perfectly.

Any ideas? Thanks

2
  • Is routes.js in your current directory? Throw a quick line prior to initializing express checking if routes is undefined or not. Could just be a pathing problem. Commented Aug 19, 2013 at 23:22
  • @Joe yeah the pathing is correct as far as I tell. It loads index.js (and then index.html) just fine. The location for play.js and play.html is the same as for index Commented Aug 19, 2013 at 23:27

1 Answer 1

6

The issue is probably that routes.play is undefined when a function is expected.

console.log(typeof routes.play); // ...

If your routes are split into multiple files as at least the comment, "index.js and play.js," suggests:

// routes/index.js
exports.index = function(req, res){
  res.sendfile('views/index.html');
};
// routes/play.js
exports.play = function(req, res){
  res.sendfile('views/play.html');
};

Requiring a directory will normally only include the index.js. So, you'll still need to require('./play') yourself somewhere.

  1. You can either "forward" it within index.js:

    exports.index = function(req, res){
      res.sendfile('views/index.html');
    };
    
    var playRoutes = require('./play');
    exports.play = playRoutes.play;
    

    Alternatively:

    exports.play = require('./play');
    
    app.get('/play', routes.play.play);
    
  2. Or require it directly in app.js as well:

     var express = require('express')
      , routesIndex = require('./routes')
      , routesPlay = require('./routes/play')
    // ...
    
    // Routing
    app.get('/', routesIndex.index);
    app.get('/play', routesPlay.play);
    
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man that was it. When I console.log(typeof routes.play) it gave me undefined. So I split it up as per option 2. Thanks man, you helped clear it up for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.