Search code examples
javascriptnode.jsjsonapiitunes

Issue with iTunes Search Api - Uncaught (in promise) SyntaxError: Unexpected end of input


I am trying to go through some tutorials about integrating APIs and creating some mini-apps in JS. The issue is that I have encountered an issue when trying to fetch some basic data from the API.

The console error that I am getting is: Uncaught (in promise) SyntaxError: Unexpected end of input at script.js:4

I would really appreciate a helping hand.

Here's my code:

const url = 'https://itunes.apple.com/search?term=ATB';

fetch(url, {mode: "no-cors"})
    .then ( (response) => response.json() )
    .then((data) => {
        console.log(data.results)
    });

Solution

  • iTunes Search Api returns a file instead of the simple JSON. You can get the data with the help of JSONP request.You cannot call it with the fetch api.

    You have to create a script tag dynamically with the src url and a callback function.

    JSONP stands for JSON with Padding. Requesting a file from another domain can cause problems, due to cross-domain policy. Requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest object

    The JSONP will trigger the callback once it's done with loading the file.

    Example:

    function clickButton() {
      var s = document.createElement("script");
      s.src = "https://itunes.apple.com/search?term=ATB&limit=2&callback=callbackHandler";
      document.body.appendChild(s);
    }
    function callbackHandler(data) {
      console.log(data);
    }
    <button type="button" onclick="clickButton()">Get Data</button>

    You could also use third party libraries for this like. fetch-jsonp

    You could also use JQuery getJSON method to get the data from api.

    Example:

    function clickButton() {
      let url = "https://itunes.apple.com/search?term=ATB&limit=2&callback=?";
      $.getJSON(url, function(data) {
        console.log(data);
      });
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button type="button" onclick="clickButton()">Get Data</button>