Twitch API on localhost (Wampserver)

I don’t have much web programming experience but I am trying to retrieve the top 8 streamers for Hearthstone and I am getting the following error.

XMLHttpRequest cannot load https://api.twitch.tv/kraken/streams?game=Hearthstone:+Heroes+of+Warcraft&limit=8. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

Here’s the code that I’m using:

$.getJSON('https://api.twitch.tv/kraken/streams?game=Hearthstone:+Heroes+of+Warcraft&limit=8', function(data) {
        var items = [];
        $.each(data, function(key, val) {
            items.push("<li id='" + key + "'>" + val + "</li>");
        });

        $("<ul/>", {
            "class": "my-new-list",
            html: items.join("")
        }).appendTo("body");
    });

I can view the JSON object on a web browser but it seems that I can’t do it on localhost. Need help!

By default (and rightly so), CORS is disabled.
You will have to use JSON-P to circumvent this. (Twitch docs)
The default way to do it with jQuery is setting callback=? in the url, and it will automatically use some JSON-P magic. (jQuery Docs)

EDIT: Good page on CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

1 Like

Thanks for the hint! I can finally see some data. I think the API docs could use a more noob-friendly example.

Here’s a very simple code I came up with to get the names of the top 8 streamers for Hearthstone:

$(document).ready(function($) {
    $.getJSON('https://api.twitch.tv/kraken/streams?game=Hearthstone:+Heroes+of+Warcraft&limit=8&callback=?', function(data) {

        for (var i = 0; i < data.streams.length; i++) {
            console.log(data.streams[i].channel.name);
        }
    });
}

Thank you for an incredibly thorough response!