1

This is the structure of my project.

app
  -controllers
      index.server.controller.js
  -models
  -routes
     index.server.routes.js
 -views
     index.ejs
config
  -express.js

I set the view directory in my express.js file:

app.set('views', '../app/views');
app.set('view engine', 'ejs');

And this is in my controller file:

exports.render = function(req,res) {
res.render('index' ,  {
    title: 'welcome to this page'
})
};

Whenever i open localhost i get

Error: Failed to lookup view "index" in views directory "../app/views/"

Aymen Rizwan
  • 47
  • 1
  • 7

1 Answers1

2

You're giving it a wrong path. Try this

app.set('views', __dirname + '/../app/views');
Bidhan
  • 10,607
  • 3
  • 39
  • 50
  • It worked but i still dont understand how it was a wrong path. Iv used the path : require('../app/routes/index.server.routes.js')(app); in the same express.js file and it works. – Aymen Rizwan Jun 24 '15 at 12:31
  • __dirname will give you the path of the current file that is executing which in your case is express.js . Without setting __dirname, your computer will have no idea where to start looking for your app/views folder. – Bidhan Jun 24 '15 at 12:32
  • But how does it work in the case of require('../app/routes/index.server.routes.js')(app); in the same file. I thought .. goes back one directory. – Aymen Rizwan Jun 24 '15 at 12:35
  • Because when you do require('../app...), you're just playing around in the file level and you can use relative paths like that. But when you do `app.set`, you can't use relative paths because now you're running a server and the server needs the location of your absolute path which is given to you by _-dirname. I know this can be a bit difficult to wrap your head around. – Bidhan Jun 24 '15 at 12:36
  • `app.set('views', __dirname + '/views');` even shorter version. – Hasan Sefa Ozalp Jan 31 '20 at 01:34