Javascript 无法使用react生产版本读取JSON文件
我有一个简单的react组件,其中我正在读取一个JSON文件。该文件被放置在公用文件夹中,如下所示Javascript 无法使用react生产版本读取JSON文件,javascript,reactjs,components,Javascript,Reactjs,Components,我有一个简单的react组件,其中我正在读取一个JSON文件。该文件被放置在公用文件夹中,如下所示 root/public/data.json class DspTable extends Component { componentDidMount() { fetch('data.json').then(response => { response.json().then(res=> { this.setStat
root/public/data.json
class DspTable extends Component {
componentDidMount() {
fetch('data.json').then(response => {
response.json().then(res=> {
this.setState({ stats: res, loading: false })
})
})
}
..
}
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowPublicReadAccess",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::bucket-name/*"
}
]
}
我正在读类似这样的JSON文件
root/public/data.json
class DspTable extends Component {
componentDidMount() {
fetch('data.json').then(response => {
response.json().then(res=> {
this.setState({ stats: res, loading: false })
})
})
}
..
}
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowPublicReadAccess",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::bucket-name/*"
}
]
}
当我在本地运行react应用程序时,这一切都非常有效
$ yarn start
但是,我需要构建站点并将其部署到s3(静态托管)
所以我构建了这个应用程序
$ yarn build
我看到build文件夹中复制了data.json和index.html
但是,当我打开build文件夹中的index.html时,我没有看到任何内容,因为没有从JSON加载数据
如何在产品构建中加载JSON文件
我使用的是React版本17.0.0
编辑:这是我的错误。我错过了s3 bucket中的bucket策略
如果将来有人面临类似问题,请使用类似的桶策略
root/public/data.json
class DspTable extends Component {
componentDidMount() {
fetch('data.json').then(response => {
response.json().then(res=> {
this.setState({ stats: res, loading: false })
})
})
}
..
}
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowPublicReadAccess",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::bucket-name/*"
}
]
}
是否尝试双击index.html以启动该文件?如果是这种情况,它将无法工作,因为浏览器将阻止加载json文件。您需要使用服务器(例如。http://localhost:3000).控制台中是否有任何错误?JSON从何而来?你做了什么调试?
res
的值是多少?