user1427661
user1427661

Reputation: 11774

Dealing with Origin http://localhost is not allowed by Access-Control-Allow-Origin Without CORS header

So I've got a simple getJSON() function:

            $.getJSON(apiURL, function(data) {
                 console.log('success');
                if (data.results.length > 0) {
                    $(song).find('source').attr('src', data.results[0].previewUrl);
                    song.play();
                }
                else {
                    console.log('No match found for track information specified.');
                }
            });

apiURL is an itunes API url, defined like this:

            var apiURL =" https://itunes.apple.com/search" +
                "?term=" + artist + "+" + album + "+" + title +·
                "&media=music&entity=musicTrack&callback=?";

I'm getting the classic Origin localhost is not allowed by Access-Control-Allow-Origin error. I've dug for some answers on this, and they usually boil down to either using $.ajax and setting the dataType to 'jsonp', or using .getJSON and supplying a 'callback=?' parameter to the URL, which I've tried above. Neither of those seem to be working, and I've heard rumblings that they may be outdated. What is the most current, up to date advise on dealing with this problem? Besides collecting the data on the server.

Upvotes: 2

Views: 3959

Answers (3)

Gaurang Jadia
Gaurang Jadia

Reputation: 1516

Browser will request server with OPTIONS method. Server has to response following headers to support CORS.

  1. Access-Control-Allow-Headers : Accept
  2. Access-Control-Allow-Methods : *
  3. Access-Control-Allow-Origin : *

If we request https://itunes.apple.com/search URL with OPTIONS method. It responses with error that not Supported.

Screenshot: https://blog.gaurangjadia.com/wp-content/uploads/2013/10/itunes.apple_.com_.png

Upvotes: 1

Jason P
Jason P

Reputation: 27012

You have a space at the beginning of your api url... once I removed that, the call went through:

http://jsfiddle.net/UU8tT/

var apiURL = "https://itunes.apple.com/search" +

Upvotes: 5

pete
pete

Reputation: 25081

Try using the full .ajax method, rather than the .getJSON shorthand method:

var terms = ["Halestorm"];
terms.forEach(function (val, i, arr) {
    terms[i] = encodeURIComponent(val);
});
$.ajax({
    "url": "https://itunes.apple.com/search",
    "dataType": "jsonp",
    "data": {
        "term": terms.join('+'),
        "media": "music",
        "entity": "musicTrack"
    },
    "error": function (jqXHR, textStatus, message) {
        console.log(message);
    },
    "success": function (data, textStatus, jqXHR) {
        console.log(data);
    }
});

The above works for me in the browser console (while on stackoverflow). It also works on jsFiddle: http://jsfiddle.net/xYthU/

Upvotes: 3

Related Questions