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
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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With