David Mckee David Mckee - 4 months ago 7
Node.js Question

How to set the default views folder in express?

I am having a lot of trouble getting my routes to direct correctly.

This is my code:

in express.js

app.set('views', config.root + '/app/views')
app.set('view engine', 'jade')


in routes.js

module.exports = function (app) {
// home route
app.get('/', home.index)
}


I keep on getting an error saying that home is not defined, even though I believe that I set the views correctly. Any idea on what the mistake may be.

If it helps, my file structure for my views is under app/views and my config files are config/express.js and config/routes.js

Answer

In your routes.js you have not defined home so you will certainly get undefined error. Views does not have anything to do with request handler. You will use res.render inside your request handler to render the view. Please look in to express.js guide to get started.

Are you trying to do this?

module.exports = function (app) {
  // home route
  app.get('/', function(req, res){
    res.render('home');
  });
}

If your request handlers are in separate module you can do this: if your home request handler is home.js in same path as routes.js you can do following.

Your route.js file

var home = require('./home');//path to your home request handler module
module.exports = function (app) {
  // home route
  app.get('/', home.index)
}

Your home.js file

exports.index = function(req, res){
  res.render('home/index');
}

It will expect you have index.jade view file in your /app/views/home folder.