Unable to run localhost:3000 in node.js app, Error: Failed to lookup view "home" in views directory "./views"

Unable to run localhost:3000 in node.js app, Error: Failed to lookup view "home" in views directory "./views"

我正在尝试通过 localhost:3000 显示我的 nodejs 应用程序。

我的主要 JS 文件是 "app.js"。我 运行 在终端中这样: "node app" 并且响应是 "server run",但是 当我在浏览器中键入 "localhost:3000" 时,终端显示此错误消息: "Error: Failed to lookup view "home" in views directory "C:...\views". 然后我在终端 "npm start" 中 运行,得到与 "server run" 相同的响应,然后是相同的 localhost:3000 浏览器错误:"Error: Failed to lookup view "home" 在视图目录 "C:...\views".

我安装了那些软件包: (1) npm init y-,然后 package.json,(2) express-handlebars(并添加了 views\main.handlebar + views\home.handlebars 文件)。

我在文件 app.js 中的代码如下:

const express = require('express');
const exphbs = require('express-handlebars');
const app = express();

app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');

app.use(express.static('public'));

app.get('/', (req, res) => {
  res.render('home', { title: 'Home Page' });
});

app.get('/about', (req, res) => {
  res.render('about', { title: 'About Us Page' });
});

app.listen(3000, () => console.log('server run!'));

This is the printscreen that maybe will help more

查找问题here, here and here并没有帮助我解决我的问题。 L 应该如何修复并在我的浏览器中正确设置 localhost:3000 运行?

您的 home.handlebars 文件在错误的文件夹中。

正如您从错误消息中看到的那样,它应该被找到为 views/home.handlebars,但是您却在 views/layouts/home.handlebars!

中找到了它

views/layouts 文件夹应仅包含布局(例如您的 main.handlebars 显然已配置为布局)。

(我想 about.handlebars 文件也应该放在 views 中...)

它应该看起来像这样: