简体   繁体   English

无法使用反应生产版本读取 JSON 文件

[英]Cant read JSON file with the react production build

I have a simple react component where I am reading a JSON file.我有一个简单的反应组件,我正在读取一个 JSON 文件。 The file is placed inside the public folder like this该文件像这样放置在公共文件夹中

root/public/data.json 

And I am reading the JSON file something like this我正在阅读类似这样的 JSON 文件

class DspTable extends Component {
  componentDidMount() {
    fetch('data.json').then(response => {
            response.json().then(res=> {
                this.setState({ stats: res, loading: false })
            })
        })
   }

 ..
}

This all works perfectly when I am running the react app locally当我在本地运行 react 应用程序时,这一切都很完美

$ yarn start

However I need to build the site and deploy it to s3 (static hosting).但是,我需要构建站点并将其部署到 s3(静态托管)。

So I build the app所以我构建了应用程序

$ yarn build

I see that the build folder has data.json copied along with index.html.我看到构建文件夹将 data.json 与 index.html 一起复制。

However when I open the index.html inside the build folder, I don't see any content as no data is loaded from the JSON.但是,当我打开 build 文件夹中的 index.html 时,我看不到任何内容,因为没有从 JSON 加载数据。

How do I load the JSON file with the production build?如何使用生产版本加载 JSON 文件?

I am using React version 17.0.0.我正在使用 React 版本 17.0.0。

Edit: It's my mistake.编辑:这是我的错误。 I was missing the bucket policy in s3 bucket.我错过了 s3 存储桶中的存储桶策略。

If anyone in the future face similar issue, please use the bucket policy like this如果将来有人遇到类似问题,请使用这样的存储桶策略

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowPublicReadAccess",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucket-name/*"
        }
    ]
}

Are you trying to double-click the index.html to launch the file?您是否尝试双击 index.html 来启动该文件? If that is the case, it won't work as the loading of json file will be blocked by the browser.如果是这种情况,它将无法工作,因为浏览器会阻止 json 文件的加载。 You would need to run the build package using a server (eg http://localhost:3000).您需要使用服务器(例如 http://localhost:3000)运行构建包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM