Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" } 
like image 753
iamsaksham Avatar asked May 17 '16 07:05

iamsaksham


People also ask

How do I fix unexpected token a JSON at position 0?

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.

What is Unexpected token in JSON at position 0?

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.

What is uncaught SyntaxError unexpected token?

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.


1 Answers

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");}); } 
like image 50
Abdennour TOUMI Avatar answered Oct 04 '22 02:10

Abdennour TOUMI