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" }
The "Unexpected token u in JSON at position 0" error occurs when we pass an undefined value to the JSON. parse or $. parseJSON methods. To solve the error, inspect the value you're trying to parse and make sure it's a valid JSON string before parsing it.
Re: Unexpected token in JSON at position 0 This usually means that an error has been returned and that's not valid JSON. Check the browser developer tools console and network tabs. Turn on Debugging and (after reproducing the error) check the web server error logs.
The "Uncaught SyntaxError: Unexpected token" occurs for multiple reasons: Having a <script /> tag that points to an HTML file instead of a JS file. Getting an HTML response from a server where JSON is expected. Having a <script /> tag that points to an incorrect path.
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");}); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With