React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
I want to fetch my Json file in react js, for this I am using fetch
. But it shows an error
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
What could be the error, i am getting no clue. I even validated my JSON.
handleGetJson(){
console.log("inside handleGetJson");
fetch(`./fr.json`)
.then((response) => response.json())
.then((messages) => {console.log("messages");});
}
My Json (fr.json)
{
"greeting1": "(fr)choose an emoticon",
"addPhoto1": "(fr)add photo",
"close1": "(fr)close"
}
Solution 1:
Add two headers Content-Type
and Accept
to be equal to application/json
.
handleGetJson(){
console.log("inside handleGetJson");
fetch(`./fr.json`, {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((messages) => {console.log("messages");});
}
Solution 2:
The solution that worked for me is that:- I moved my data.json file from src to public directory. Then used fetch API to fetch the file.
fetch('./data.json').then(response => {
console.log(response);
return response.json();
}).then(data => {
// Work with JSON data here
console.log(data);
}).catch(err => {
// Do something for an error here
console.log("Error Reading data " + err);
});
The problem was that after compiling react app the fetch request looks for the file at URL "http://localhost:3000/data.json" which is actually the public directory of my react app. But unfortunately while compiling react app data.json file is not moved from src to public directory. So we have to explicitly move data.json file from src to public directory.