Search code examples
javascriptiosangularjshttp-get

How can I query the iTunes search API in javascript?


I am trying to query the App Store for information on a given app, however I keep getting the following error.

XMLHttpRequest cannot load https://itunes.apple.com/lookup?id=<some-app-id>. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://www.<some-website>.co.uk' is therefore not allowed access. The response had HTTP status code 501.

The code I'm using to execute the request is as follows.

Does anyone know where I may be going wrong?

var config = {
        headers:  {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET',
            'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With',
        }
    };

    $http.get("https://itunes.apple.com/lookup?id=<some-app-id>", config).success(
        function(data) {
            // I got some data back!
        }
    );

Solution

  • Edit: here's a plunker showing my successful approach roughly getting it into an AngularJS app:

    http://plnkr.co/edit/QhRjw8dzK6Ob4mCu6T6Z?p=preview

    Adding those headers to your server won't change what is happening. The cross origin headers need to be added by the iTunes API.

    That is not going to happen, so what you need to do instead is to use JSONP style callbacks in your webpage. There is an example on the iTunes search API page.

    http://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html

    Note: When creating search fields and scripts for your website, you should use dynamic script tags for your xmlhttp script call requests. For example:

    <script src="https://.../search?parameterkeyvalue&callback="{name of JavaScript function in webpage}"/>
    

    Note the 'callback' parameter there. That is a function defined globally in your javascript on the page that will get called with the response from the request to the url in 'src'. That function puts the data into your page, or application. You'll have to figure out how.

    It's a shame that the language used in this documentation is not clearer, because you must do some kind of JSONP style workaround since they don't have CORS enabled on their API.

    If you need to dynamically add a script tag (fetching data once is not enough) you can try this tutorial:

    Dynamically add script tag with src that may include document.write

    The API in general is probably intended for use by backends (not affected by cross origin issues), not for client side fetching.