从公用文件夹ReactJS获取本地JSON文件 [英] Fetch local JSON file from public folder ReactJS

查看:571
本文介绍了从公用文件夹ReactJS获取本地JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两天的问题;我希望在使用react-app创建的React应用程序中从我的公共文件夹中读取本地JSON。

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.

这是我的项目结构:


  • 公开

  • public


  • 数据

  • data


  • mato.json(我的.JSON文件)

src


  • 组件

  • components


  • App.js

为什么我将文件放在 public 文件夹中?如果我使用 src 文件夹中的文件构建我的项目,我的文件将包含在生成的 main.js 中。命令纱线构建

Why I put my file in public folder? If I build my project with file in src folder, my file will be include in the generated main.js by the command yarn build.

我想修改我的json文件,而不是总是重建我的应用程序。

I want modify my json file without always rebuild my app.

所以我不能使用如下代码:

So I can't use code like:

import Data from './mato.json'

...或者:

export default { 'mydata' : 'content of mato.json'}
import data from 'mydata';

我试图获取我的.json文件,但文件方案不是<$ c的朋友$ c> fetch()& chrome ..

I tried to fetch my .json file but "file scheme" isn't friend with fetch() & chrome..

(Chrome错误:index.js:6 Fetch API无法加载文件:/// D:/projects/data/mato.json.URL方案file不受支持。)

(Chrome error: "index.js:6 Fetch API cannot load file:///D:/projects/data/mato.json. URL scheme "file" is not supported.")

这是我的fetch代码:

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'));
})

它仅适用于Firefox。我也试过模式:'cors'并不是更好。

It's only works with Firefox. I also tried mode: 'cors' does not better.

当然我没有任何服务器 - 这是一个本地项目 - 所以如果有人知道如何在本地阅读我的JSON文件,我将非常感激。

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.

推荐答案

我认为你的fetch参数是错误的。它应该是

I think your fetch argument is wrong. It should be

fetch('data/mato.json')

这篇关于从公用文件夹ReactJS获取本地JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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