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
Iterate Through Nested JavaScript Objects
JavaScript Objects: Get Parent
Memory Leak Risk in JavaScript Closures
Why Does (0 < 5 < 3) Return True
Jquery Ajax Call to PHP Script with JSON Return
How to Open a New Window and Insert HTML into It Using Jquery
Securityerror: the Operation Is Insecure - Window.History.Pushstate()
Formdata.Append("Key", "Value") Is Not Working
How to Determine If a Checkbox Is Checked
How to Download a File Using Window.Fetch
Convert Base64 to Image in JavaScript/Jquery
Array VS. Object Efficiency in JavaScript
Webhoster Inserts a JavaScript Which Brokes My Code How to Remove It