【问题标题】:Failed to lookup view "home/index" in views directory "/app/views"在视图目录“/app/views”中查找视图“home/index”失败
【发布时间】:2019-08-30 13:20:05
【问题描述】:

我正在尝试将我的项目发布到 heroku 以使其在云中运行。在本地,它在端口 5000 上工作,我可以获得每个视图。当我将它上传到heroku时,当我尝试访问主页时出现以下错误:无法在视图目录“/app/views”中查找视图“home/index”

我已经尝试过以下操作:

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs'); // set up ejs for templating

我也在互联网上寻找其他解决方案,但似乎没有任何东西可以解决我的问题。

我的路线是这样的:

  • views/home/index.ejs

查找文件的代码是:

        app.get('/', function (req, res) {
            res.render('home/index.ejs'); // load the index.ejs file
        });

预期的输出是我的 heroku 工作正常,无需进行大的更改,因此它既可以在 heroku 上工作,也可以在本地工作。目前 heroku 正在返回上述错误。

【问题讨论】:

标签: node.js express heroku ejs


【解决方案1】:

不要使用res.render(),而是使用res.sendFile().. 如下所示

res.sendFile(path.join(__dirname+'/home/donnyllionaire/CRUD-app-Nodejs-Express-and-MongoDB/employee/addOrEdit.html'));

有关更多说明,请参阅此链接:https://github.com/donnillionaire/CRUD-app-Nodejs-Express-and-MongoDB/commit/11704d4572b7acc18b7289103b71282c58358d9a

【讨论】:

    【解决方案2】:

    这是因为 Heroku 在 views 文件夹中找不到子文件夹 home。这很可能是因为您可能将文件夹写为“Home”而不是“home”。要找出答案,请执行heroku run bash,然后运行ls。这将列出 /app 文件夹中的文件夹。进入工作目录后,您应该会看到 views 文件夹。执行cd views,您将获得所有文件夹的列表。在那里你应该找到home 文件夹。如果您找到Views 而不是viewsHome 而不是home,那么这就是错误的来源,因为在heroku中,文件夹和文件路径区分大小写(在本地不是这就是为什么您不会在 localhost 端口 5000 中遇到相同错误的原因)。

    将文件夹和文件名修改为适当的大小写后,在 Heroku 上进行推送,它应该可以工作。还要小心再次测试,看看heroku run bash 是否有效,cd home 有效。如果没有,那么您需要删除 home 文件夹,推送到 Heroku,然后重新粘贴 home 文件夹并进行推送(因为缓存),然后它应该可以工作了。

    【讨论】:

      【解决方案3】:

      您尝试过 app-module-path 吗?

      const path = require('path');
      require('app-module-path').addPath(path.join(__dirname, '../'));
      
      
      I do not possess any experience with Heroku but the error seems to be related with a 
      path problem like assuming there is a different directory level.
      I would try to debug it on the render method and then go for a module solution.
      

      举例

      app.get('/', function (req, res) {
          res.render('../home/index.ejs'); // load the index.ejs file
      }); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-14
        • 2016-07-18
        • 1970-01-01
        • 1970-01-01
        • 2016-01-27
        • 2016-08-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多