11

I am trying to learn node.js.

I have the following code.

var express = require('express');
var app = express();

var port = process.env.PORT || 5000;

app.use(express.static('public'));
app.use(express.static('src/views'));

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

app.get('/', function(req, res) {
    res.render('index', { title: 'Hello from render', nav: ['Books', 'Author'] });
});

Failed to lookup view "index" in views directory I have the file named index.ejs. How can I get rid of this error?

user2281858
  • 1,957
  • 10
  • 41
  • 82

6 Answers6

13

Try with

app.set('views', __dirname + '/views');
Oscar
  • 13,594
  • 8
  • 47
  • 75
  • like this `app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); ` – user2281858 Apr 13 '16 at 20:44
  • This solved it for me.. I was running express in a different module – Chris Barry Dec 19 '18 at 21:31
  • Could you please mention, in which file I have to write this code? In server.ts file I found similar codes but starting with `server.***`, not app.*** – Satrughna Jan 13 '21 at 12:06
  • @Satrughna It depends on your codebase, so I don't know in your specific case. This needs to be specified on the file where you're instantiating and configuring the express instance. – Oscar Jan 13 '21 at 15:58
7

This is how I fixed it.

app.set('views', './src/views');
app.set('view engine', 'ejs');
user2281858
  • 1,957
  • 10
  • 41
  • 82
2

I had the same problem too. I have saved the index file as .html file. But it should be index.ejs. then it worked. Check that too

maneesha
  • 145
  • 2
  • 4
  • 12
0

For me it was a banal problem: when I named my 'views' folder, accidentally I typed a white space before the name, so the name was ' veiws', thus, ejs couldn't find the 'views' folder.

Ador
  • 11
  • 1
  • 2
0

i fixed this error by writing below line befor my app.set('viewengine' , 'ejs')

    app.set('views',path.join(__dirname,'views'));

using path is more convenient ,also note to require path befor using it

Mohammed
  • 838
  • 6
  • 14
0

I had the same issue, then I saved my index file inside the views folder. Now the issue is gone. Also add this line of code in your file app.set('views', path.join(__dirname, '/views'))

0xLogN
  • 3,289
  • 1
  • 14
  • 35