【问题标题】:NodeJS - Trying to render index.ejs file, but still only servers index.html that is in my public folderNodeJS - 试图呈现 index.ejs 文件,但仍然只有我的公共文件夹中的服务器 index.html
【发布时间】:2018-03-10 18:21:14
【问题描述】:

下面的代码仍然为public 文件夹中的index.html 页面提供服务,但我想渲染index.ejs。我按照视频示例进行操作,所以我不确定他为什么能够渲染 ejs 文件,而我仍然只能看到 index.html 文件。

我使用的视频示例似乎是相同的。我的package.json 文件有"main": "app.js"

这是视频示例链接,代码如下: https://youtu.be/gnsO8-xJ8rs?t=28m12s

//View Engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

//Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : false}));

//Set Static path
app.use(express.static(path.join(__dirname, 'public')));

//Routes
app.get('/', (req, res) => {//homepage represented by the single slash
  res.render('index');
});

app.listen(3000, () => {
  console.log('server started on port 3000...');
});

我注意到如果我注释掉

//Routes
app.get('/', (req, res) => {//homepage represented by the single slash
  res.render('index');
});

然后渲染并提供 ejs 文件。

任何建议将不胜感激!

【问题讨论】:

  • 我的假设是因为你的静态路径取消注释路由并包含文件路径到你的目录例如./../views/index.ejs

标签: javascript node.js express ejs


【解决方案1】:

请注意,默认情况下 EJS 会查看“Views”文件夹

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

您可以指定要在文件夹中查看的文件路径,因为 Views 将其更改为您的 public 文件夹,它将启动并运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 2020-04-15
    相关资源
    最近更新 更多