Home > Mobile >  React fetch local json file for testing does not work
React fetch local json file for testing does not work

Time:12-11

I'm trying to fetch a .json file from local, and

I get response 200 but with a body response of HTML: "You need to enable JavaScript to run this app."

I have javascript enabled of course.

I don't want to import the file to simulate the real fetch.

How does local fetch work in react? How do I know if the fetch route is right? It doesn't give any useful error hint.

    useEffect(() => {
    const getData = async () => {
        const dataFromLocal = await fetchData();
        console.log('dataFromLocal', dataFromLocal);
    }
    getData();
}, [])

const fetchData = async () => {
    const response = await fetch('data.json');
    const data = await response.json();
    return data;
}

CodePudding user response:

I found how it works:

        const response = await fetch('data.json',
           {headers: 
               {'Content-Type': 'application/json','Accept': 'application/json'}
           });

just add this headers object to the fetch method and it works

CodePudding user response:

There are only two possibilities based on the code you've shown:

  1. Your server is responding with the contents of an HTML resource (likely index.html) as the response to the request for data.json, or

  2. data.json looks like this, the JSON string you provided:

"You need to enable JavaScript to run this app."

Is data.json in your project's ./public folder?

  • Related