I am working through Amos Q. Haviv's MEAN Web development textbook. It was going fine, but I ran into an error working with Express.js that I can't seem to find an answer for online. There are no comments about the book or anything that outline this error, and I can't find any helpful answers. I'm working on a simple index page:
Version of Express used in the book is: 4.8.8 My latest version is: 4.12.4
Controller:
var express = require('express');
var hasName = function(req, res, next) {
if (req.params.name) {
next();
} else {
res.send('What is your name?');
}
};
var sayHello = function(req, res, next) {
res.send('Hello ' + req.params.name);
};
var app = express();
app.get('/', hasName, sayHello);
app.listen(3000);
console.log('Server running at http://localhost:3000/');
Route:
module.exports = function(app) {
var index = require ('../controllers/index.server.controller');
app.get('/', index.render);
};
Express config file:
var express = require('express');
module.exports = function() {
var app = express();
require('../app/routes/index.server.routes')(app);
return app;
};
Server.js:
var express = require('./config/express');
var app = express();
app.listen(3000);
module.exports = app;
console.log('Server running at http://localhost:3000/');
And finally, the error message that comes up when I start the server:
Error: Route.get() requires callback functions but got a [object Undefined]
at Route.<anonymous> (...\node_modules\express
\lib\router\route.js:170:15)
at Array.forEach (native)
at Route.(anonymous function) [as get] (...\no
de_modules\express\lib\router\route.js:166:15)
at EventEmitter.app.(anonymous function) (...\
node_modules\express\lib\application.js:465:19)
at module.exports (...\app\routes\index.server
.routes.js:3:9)
at module.exports (...\config\express.js:5:49)
at Object.<anonymous> (...\server.js:3:11)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
The point of failure seems to be that when
app.get('/', index.render);
Is called, it errors out because index is undefined/an empty object. I have not been able to determine why this is happening.
If I export the app end of the controller .js file with module.exports, the server will start up, but will later error out with something else. I have tried everything I can think of to fix this, including copy-pasting the examples from the book exactly. I really want to be able to follow the book until I can grasp this development stack. Any help is appreciated.
Obviously this module :
require ('../controllers/index.server.controller')
,
is not exporting an object which defines any render
property / function.
Ensure this module exports a render
function with this signature:
...
module.exports = { render: function(req, res, next) {...}, ... }
...