Fetch Request to Local File Not Working

Fetch request to local file not working

I was encountering the same error and there are two changes I made in my code to get rid of the error. Firstly, you don't need an express server to serve your files you can read data from a local json file inside your public folder in your create-react-app directory.

  const getData=()=>{
fetch('data.json',{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}
)
.then(function(response){
console.log(response)
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
}
useEffect(()=>{
getData()
},[])

First, as suggested in some of the answers above ensure that your json file is inside the public folder and the path parameter inside the fetch function is correct as above. Relative paths didn't work for me.
Second, set the headers as shown. Removing the headers part from my fetch call was still giving me this error.

Can't fetch local file

You should put your tsv file to the public folder of your project if you're using create-react-app for example. If you're not. You need to serve that file for it to be available for the fetch

Please, check this question/aswer

fetch json local file get 404 not found

try using just data.json or try multiple options. Also, leave your JSON file outside of the current file.

React fetch local json file for testing does not work

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



Related Topics



Leave a reply



Submit