Search code examples
reactjsjsonfetchlocal

React fetch local json file for testing does not work


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

Solution

  • 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