I'm just experimenting with basic routing in ExpressJS and so far I have two routes:
app.get('/', function(req,res) {
res.render('index');
});
app.get('/pics', function(req,res) {
res.render('pics');
});
When defined like this, in my app.js, everything works fine, but when exported as below, from individual files in my routes
subdirectory, I get the error message that a callback function was expected, but an Object undefined was returned.
index.js:
exports.index = function(req,res) {
res.render('index');
});
pics.js
exports.pics = function(req, res) {
res.render('pics');
};
app.js
var routes = require('./routes');
app.get('/', routes.index);
app.get('/pics', routes.pics);
What am I doing wrong in the latter example to break everything?
The index route is working but your pics route isn't because you are trying to import it from index.js.
The route directory has index.js which means that if you do require('./route')
you are actually doing require('./route/index')
. This happens because index.js has a special meaning in Node.js.
So to get pics working you need to do:
app.get('/pics', require('./routes/pics').pics);
This can be really confusing and is a question that gets asked a lot on the IRC channel.