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"
}
Mostly this is caused with an issue in your React/Client app. Adding this line to your client
package.json
solves itNote: Replace 5000, with the port number where your server is running
Reference: How to get create-react-app to work with a Node.js back-end API
Add two headers
Content-Type
andAccept
to be equal toapplication/json
.This error can be received but be aware it can be a red herring to the real issue. In my case, there wasn't an issue with the JSON as the error states, but rather a 404 was occurring that it could not pull the JSON data to process in the 1st place thus resulting in this error.
The fix for this was that in order to use
fetch
on a.json
file in a local project, the.json
file must be accessible. This can be done by placing it in a folder such as thepublic
folder in the root of the project. Once I moved thejson
file into that folder, the 404 turned into a 200, and theUnexpected token < in JSON at position 0
error was resolved.It may come when the API(you are consuming) is not sending the corresponding JSON. You may experience the response as 404 page or something like HTML/XML response.
I was getting the same error, for me, it was because API was just returning a string however in fetch call I was expecting json :
Returning json from API resolved the issue for me, if your API is not supposed to return json then simply don't do
response.json()
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.
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.