javascriptjsonajaxreactjs

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

  • 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");});
    }