Nodejs/Express: Error: Failed to lookup view “error” in views directory

巧了我就是萌 提交于 2019-12-03 17:50:19

问题


I switched my nodejs template engine over to ejs (from jade). When I run my app.js with my ejs template, I receive a series of "Failed to lookup view 'error' in views" logs.

Some of which include:

GET /css/bootstrap.min.css 500 12.588 ms - 1390
Error: Failed to lookup view "error" in views directory
...
GET /css/clean-blog.min.css
Error: Failed to lookup view "error" in views directory
...
GET /js/bootstrap.min.js
Error: Failed to lookup view "error" in views directory
...
GET /js/jquery.js
Error: Failed to lookup view "error" in views directory

Thing is, many of these dependencies are included in the template itself (included via script tags). What is the proper place to get these to work in express? It seems like express ultimately should not be looking for these in the views folder (since they aren't views).


回答1:


Make sure your Express App has this setup, for the current layout it sounds like you have.

// Require static assets from public folder
app.use(express.static(path.join(__dirname, 'public')));

// Set 'views' directory for any views 
// being rendered res.render()
app.set('views', path.join(__dirname, 'views'));

// Set view engine as EJS
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

It is pretty normal for views that are getting rendered by res.render() to be placed in a 'Views' directory at the top level of your app. The express-generator actually uses that view setup. You can change that by modifying the below line

// replace with the directory path below ./
app.set('views', path.join(__dirname, 'views'));



回答2:


It seems that Express doesn't find your files, so your poor little server want to return an error, but your error file is missing in views directory.

In views directory, you have just to create a file called error.jade.

Then you have to search where Express searches your files yet.




回答3:


I resolved my issue by using below code.

    // Require static assets from public folder
app.use(express.static(path.join(__dirname, 'public')));
// Set view engine as EJS
app.engine('ejs', require('ejs').renderFile);
app.set('view engine', 'ejs');
// Set 'views' directory for any views 
// being rendered res.render()
app.set('views', path.join(__dirname, ''));
app.use('/form', express.static(__dirname + '/index.html'));


来源:https://stackoverflow.com/questions/35604730/nodejs-express-error-failed-to-lookup-view-error-in-views-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!