93

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"
}
6
  • 1
    Maybe you get error page in response, look at network tab in developer tools what the response was.
    – jcubic
    May 17, 2016 at 7:33
  • 1
    Yeah. I'm getting some garbage html in fr.json.
    – iamsaksham
    May 17, 2016 at 7:36
  • 4
    Okay, I solved the issue. Firstly the .json needs to be loaded via localhost. So I changed the fetch('http://localhost/img/fr.json'). Further I was running my app on localhost:8080, so a CORS issue occurred which was taken care by disabling it via a chrome plugin. Anyway thanks a lot @jcubic for giving a heads up, because sometimes it not any fault in the code.
    – iamsaksham
    May 17, 2016 at 8:13
  • 2
    check if the data that you are loading is in JSON form (that "<" sign is telling that something, something is about XML)
    – Zack Zilic
    Feb 23, 2018 at 13:45
  • I am working on Api in React, I have changed it from await fetch(https://api.com/search?q=chicken&app_id=${APP_ID}&app_key=${APP_KEY} ) to await fetch(http://localhost:3000/https://api.com/search?q=chicken&app_id=${APP_ID}&app_key=${APP_KEY} ), but I am still getting an error saying "Unexpected token < in JSON at position 0". Even I have turned ON my Moesif Orign & CORS Changer. What should I do now. Apr 29, 2020 at 17:36

20 Answers 20

83

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");});
}
1
  • 44
    It's a GET request, so sending a Content-Type header is simply wrong. There is no content, in the request, to describe the type of. Setting the Accept header could solve the problem but few servers actual perform content-negotiation so its unlikely to help. The OP has also explicitly stated (in a comment on the question) that they were having a CORS error and were using the wrong URL so its unclear why @iamsaksham accepted this as the solution to their problem.
    – Quentin
    Jun 30, 2019 at 20:56
34

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.

1
  • 1
    This answer is the most appropriate in react js context. most don't check the 404 for json file in network. The json need to be in public directory
    – Santosh Ch
    Aug 11, 2021 at 15:29
23

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 the public folder in the root of the project. Once I moved the json file into that folder, the 404 turned into a 200, and the Unexpected token < in JSON at position 0 error was resolved.

3
  • 3
    This is what solved it for me. I had the JSON in my src folder. Moving it to public made it work.
    – LukeVenter
    Oct 22, 2019 at 8:43
  • This also worked for me. Is there a downside to doing it this way? Jul 10, 2021 at 8:45
  • Red herring for me as well.. my issue was where I was sending the request. Forgot to include https://
    – wiregh0st
    Jan 10, 2022 at 17:18
21

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 :

response => response.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()

1
  • Same here, though I'm not sure why my Flask server wasn't returning JSON
    – David Cian
    Aug 24, 2022 at 16:09
5

I also had the same issue when trying to fetch the data from "/src" folder. Moving the file into the "/public" solved the problem for me.

4

I had the same issue with fetch and decided to switch to axios. Fixed the issue right away, here's the code snippet.

var axios = require('axios');

  var config = {
    method: 'get',
    url: 'http://localhost:4000/'
  };
  
  axios(config)
  .then(function (response) {
    console.log(JSON.stringify(response.data));
  })
  .catch(function (error) {
    console.log(error);
  });
3

I had the same issue although I was requesting data from another web server and not locally. The response status code was 200 but I still didnt get the data, even though it was sent in JSON format by default. The (simple) problem was that I had forgot to include 'https://' in the url, so instead it used the local host in the beginning.

1
  • “The work you do is important and so appreciated.” “Sending a little heartfelt appreciation your way today!” “Just wanted to express our deep gratitude for the dedicated work you do day after day.” “For all you do—and for the kind, thoughtful way you do it—thank you.” Mar 17, 2022 at 0:31
2

I confirm some methods proposed here that also worked for me : you have to put your local .json file in your public directory where fetch() is looking for (looking in http://localhost:3000/) for example : I use this fetch() in my src/App.js file:

componentDidMount(){
  fetch('./data/json-data.json')
  .then ( resp1 => resp1.json() )
  .then ( users1 => this.setState( {cards : users1} ) )
}

so I created public/data/json-data.json

and everything was fine then :)

1

on your Promise response you requested

response.json() 

but this works well if your server sends json response in return especially if you're using Node Js on the server side

So check again and make sure your server sends json as response as said if its NodeJS the response could be

res.json(YOUR-DATA-RESPONSE)
1

Sometime you API backend could not respect the contract, and send plain text (ie. Proxy error: Could not proxy request ..., or <html><body>NOT FOUND</body></html>).

In this case, you will need to handle both cases: 1) a valid json response error, or 2) text payload as fallback (when response payload is not a valid json).

I would suggest this to handle both cases:

  // parse response as json, or else as txt
  static consumeResponseBodyAs(response, jsonConsumer, txtConsumer) {
    (async () => {
      var responseString = await response.text();
      try{
        if (responseString && typeof responseString === "string"){
         var responseParsed = JSON.parse(responseString);
         if (Api.debug) {
            console.log("RESPONSE(Json)", responseParsed);
         }
         return jsonConsumer(responseParsed);
        }
      } catch(error) {
        // text is not a valid json so we will consume as text
      }
      if (Api.debug) {
        console.log("RESPONSE(Txt)", responseString);
      }
      return txtConsumer(responseString);
    })();
  }

then it become more easy to tune the rest handler:

class Api {
  static debug = true;

  static contribute(entryToAdd) {
    return new Promise((resolve, reject) => {
      fetch('/api/contributions',
        { method: 'POST',
          headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
          body: JSON.stringify(entryToAdd) })
      .catch(reject);
      .then(response => Api.consumeResponseBodyAs(response,
          (json) => {
            if (!response.ok) {
              // valid json: reject will use error.details or error.message or http status
              reject((json && json.details) || (json && json.message) || response.status);
            } else {
              resolve(json);
            }
          },
          (txt) => reject(txt)// not json: reject with text payload
        )
      );
    });
  }
1

Try converting the response to string and then parse it to JSON. This solves the error for me. Below is the code for the same.

let resp = JSON.stringify(response);
res = JSON.parse(resp);
0

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.

1
  • Yes, I am getting an XML response, do you have any idea how to convert it into JSON? Apr 12, 2022 at 7:01
0

I had the .json file in src folder. Simply moved it in the public folder and it worked

0

I struggled with the same issue but then found a solution after doing some research. The issue sometimes arises from a typing error. Your console lets you know the type of error.

Here's is how I found out: In settings.py I wrote a double underscore: CORS__ORIGIN_ALLOW_ALL = True instead of CORS_ORIGIN_ALLOW_ALL = True.

The issues persisted and I changed this 'the API Fetch method' and it worked just fine:

refreshList() {
  fetch(process.env.REACT_APP_API+ "department")
    .then((response) => response.json())
    .then((data) => {
      this.setState({ deps: data });
    });
}

to:

refreshList() {
  fetch("http://127.0.0.1:8000/" + "department")
    .then((response) => response.json())
    .then((data) => {
      this.setState({ deps: data });
    });
}
1
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Sep 13, 2021 at 12:30
0

For me, I was making a call with fetch from a new computer and I forgot to add the env file to populate the process.env.REACT_APP_URL and process.env.REACT_APP_API_KEY fields. Adding back the .env file resolved the issue.

0

Add "method: 'GET'"

let query = {
      method: 'GET',
      headers: {
        authToken: token,
        "Content-Type": "application/json",
    },
 };
0

With datas in public/datas/datas.json :

export default class App extends React.Component {
    constructor(props) {
        super(props);
    }
    async componentDidMount() {
        const response = await fetch("datas/datas.json");
        const datas = await response.json();
        console.log(datas);
    }
...
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Mar 17, 2022 at 20:02
0

At first, add the line of code that is given below at the top :

const port = process.env.PORT || 3000;

make sure your fr.json inside public folder. then write the code as given below:

fetch(`http://localhost:${port}/fr.json`)
    .then((response) => response.json())
    .then((messages) => {console.log("messages");});
-1

I was getting the error. I simply added "proxy" in my package.json and the error went away. The error was simply there because the API request was getting made at the same port as the react app was running. You need to provide the proxy so that the API call is made to the port where your backend server is running.

-4

Mostly this is caused with an issue in your React/Client app. Adding this line to your client package.json solves it

"proxy": "http://localhost:5000/"

Note: 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

1
  • 3
    This does not answer the question. Jun 12, 2018 at 14:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.