Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

javascript - Fetch local JSON file from public folder ReactJS

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.

This is my project structure:

  • public

    • data

      • mato.json (my .JSON file)
  • src

    • components

      • App.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.

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

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..

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

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think your fetch argument is wrong. It should be

fetch('data/mato.json')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...