[javascript] 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"
}

This question is related to javascript json ajax reactjs

The answer is


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


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)

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

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()


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 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.


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.


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

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


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


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.


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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release