Heroku ENOENT:没有这样的文件或目录,stat'/app/build/index.html' [英] Heroku ENOENT: no such file or directory, stat '/app/build/index.html'

查看:154
本文介绍了Heroku ENOENT:没有这样的文件或目录,stat'/app/build/index.html'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在Heroku中运行一个简单的测试站点.出于某种原因,当我希望从/app/build/提供内容时,它试图从/app/build/提供内容.

I'm having trouble running a simple test site in Heroku. For some reason it's trying to serve the content from /app/build/ when I want it to serve from /build/.

错误:ENOENT:没有这样的文件或目录,stat'/app/build/index.html'

Error: ENOENT: no such file or directory, stat '/app/build/index.html'

我在此处阅读了在Express应用程序中使用__dirname,因为Heroku将其设置为/app,我应该使用process.cwd();

I read here not to use __dirname in the express app as Heroku set it to /app and that I should use process.cwd();

process.env.PWD = process.cwd();

但是没有用.下面是我的server.js Express应用程序和文件夹结构

But it didn't work. Below is my server.js express app and folder structure

const path = require('path');
const express = require('express');
const port = process.env.PORT || 8080;
const app = express();

process.env.PWD = process.cwd();

app.use(express.static(process.env.PWD + '/build'));

app.get('*', function (req, res) {
  const index = path.join(process.env.PWD, '/build/index.html');
  res.sendFile(index);
});

app.listen(port);
console.log('server_started');

推荐答案

首先,不要使用PWD.只需使用__dirname.它在Heroku上的工作原理与在其他地方一样.例如,如果您从非本地目录执行二进制文件,则使用PWD会使您的应用程序更脆弱.

First, don't use PWD. Just use __dirname. It works on Heroku exactly as it works anywhere else. Using PWD makes your app more brittle if you, for instance, execute a binary from a non-local directory.

第二,Heroku中不存在该文件的原因很可能是因为您已将其添加到.gitignore文件中,或者通常没有将其检入git中.您可以从编辑器的颜色编码中看到这一点-检入git的所有文件均为白色,被忽略的文件为灰色(例如node_modules目录和build/bundle).您的索引文件是红色的(而不是签入文件的白色).因此,当您git push heroku master时,您引用的那些文件不存在.

Second, the reason that file doesn't exist on Heroku is likely because you've added it to your .gitignore file or generally haven't checked it into git. You can see this from the color coding of your editor - all of the files checked into git are white, the ones ignored are gray (like the node_modules directory and build/bundle). Your index file is red (not white like the checked-in files). So when you git push heroku master, those files you're referencing don't exist.

最后,ENOENT说/app/build的原因仅仅是因为您在Heroku上的根目录/主目录是/app.切勿构建被锁定在绝对文件结构中的应用程序;只需使用相对路径即可(否则,即使将其移动到本地计算机上的另一个目录,您的应用程序也会中断).

Finally, the reason ENOENT says /app/build is just because your root/home directory on Heroku is /app. Never build apps that are locked into an absolute file structure; just use relative paths (otherwise, your app will break if you even move it to another directory on your local machine).

app.get('*', function (req, res) {
  const index = path.join(__dirname, 'build', 'index.html');
  res.sendFile(index);
});

这篇关于Heroku ENOENT:没有这样的文件或目录,stat'/app/build/index.html'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆