Reputation: 3607
My application is not loading the 'EJS' module when I try and invoke routing in my app.js
file and I'd like to know why.
My question is very similar in scope to this one, but it has some additional wrinkles to it that were not addressed in the answers there so I thought I'd turn this into a new question entirely.
If I start a very basic app.js
file like this that calls ejs
it works as expected and raises no errors.
APP.JS:
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.send("Hello World");
}).listen(3000, function(){
console.log("The port is now listening at 3000");
});
However, once I modify app.js
to use routes to render a view I get the error message in the title.
The following script provides the error:
APP.JS:
var express = require('express');
var app = express();
var root = require('./routes/index');
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
app.use(root);
app.listen(3000, function(){
console.log("The port is now listening at 3000");
});
module.exports = app;
My index.js file that I use to establish the route looks like this:
INDEX.JS:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', {
pageTitle: 'The Formula Generator',
pageDescription: 'Easily manage and store your supplement formulas',
pageID: 'home' });
});
module.exports = router;
EJS is correctly loaded in my package.json like so:
PACKAGE.JSON:
"dependencies": {
"body-parser": "~1.15.2",
"cookie-parser": "~1.4.3",
"debug": "~2.2.0",
"ejs": "^2.5.5",
"express": "~4.14.0",
"mongodb": "^2.2.16",
"monk": "^3.1.3",
"morgan": "~1.7.0",
"serve-favicon": "~2.3.0"
},
It's also installed in my node_modules folder as well.
My file structure currently looks like this:
Upvotes: 3
Views: 6727
Reputation: 119
Install express on root of the project .
npm install express --save
Upvotes: 1
Reputation: 12945
app.js
var express = require('express');
var app = express();
var root = require('./routes/index');
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
root(app); // pass app to index
app.listen(3000, function(){
console.log("The port is now listening at 3000");
});
module.exports = app;
index.js
var controller = function(app){
app.get('/', function(req, res) {
res.render('index', {
pageTitle: 'The Formula Generator',
pageDescription: 'Easily manage and store your supplement formulas',
pageID: 'home' });
});
};
module.exports = controller;
package.json
{
"name": "test",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "3.2.6",
"ejs": "*"
}
}
Upvotes: 2