javascript 从公共文件夹 ReactJS 中获取本地 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46793310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fetch local JSON file from public folder ReactJS
提问by Kevin
I have a problem since two days; I want read a local JSON from my public folder on my React application created with react-app.
我这两天有问题;我想从使用 react-app 创建的 React 应用程序的公共文件夹中读取本地 JSON。
This is my project structure:
这是我的项目结构:
public
data
- mato.json (my .JSON file)
src
components
- App.js
上市
数据
- mato.json(我的 .JSON 文件)
源文件
组件
- 应用程序.js
Why I put my file in publicfolder? If I build my project with file in srcfolder, my file will be include in the generated main.jsby the command yarn build.
为什么我把我的文件放在public文件夹中?如果我使用文件src夹中的文件构建我的项目,我的文件将包含在main.js命令生成的文件中yarn build。
I want modify my json file without always rebuild my app.
我想修改我的 json 文件而不总是重建我的应用程序。
So I can't use code like:
所以我不能使用如下代码:
import Data from './mato.json'
…or:
…或者:
export default { 'mydata' : 'content of mato.json'}
import data from 'mydata';
I tried to fetch my .json file but "file scheme" isn't friend with fetch()& chrome..
我试图获取我的 .json 文件,但“文件方案”不是fetch()& chrome 的朋友..
(Chrome error: “index.js:6 Fetch API cannot load file:///D:/projects/data/mato.json. URL scheme "file" is not supported.”)
(Chrome 错误:“index.js:6 Fetch API 无法加载 file:///D:/projects/data/mato.json。不支持 URL 方案“文件”。”)
This is my code for fetch:
这是我的获取代码:
fetch(`${process.env.PUBLIC_URL}/data/mato.json`)
.then((r) => r.json())
.then((data) =>{
ReactDOM.render(<App appData={JSON.stringify(data)}/>, document.getElementById('root'));
})
It's only works with Firefox. I also tried mode: 'cors'does not better.
它仅适用于 Firefox。我也试过mode: 'cors'没有更好。
And of course I don't have any server — it's a local project —?so if someone knows how I can read my JSON file locally I will much appreciate.
当然,我没有任何服务器——它是一个本地项目——所以如果有人知道我如何在本地读取我的 JSON 文件,我将不胜感激。
回答by Quentin
I think your fetch argument is wrong. It should be
我认为你的 fetch 论点是错误的。它应该是
fetch('data/mato.json')
回答by Lex Soft
As long as data files are placed in public folder, it should work in Chrome also as in my project. So, fetch('data/mato.json') is enough for it.
只要数据文件放在公共文件夹中,它就可以在 Chrome 中工作,就像在我的项目中一样。所以, fetch('data/mato.json') 就足够了。

