Ajax - “Access-Control-Allow-Origin” Error

我的梦境 提交于 2019-12-25 07:00:57

问题


I'm trying to work with the Livestream API to see if a certain channel is live but keep getting this error:

XMLHttpRequest cannot load http://channel.api.livestream.com/1.0/livestatus?channel=huskystarcraft. Origin http://www.webdevstl.com is not allowed by Access-Control-Allow-Origin.

Do I need to run it through PHP or am I doing something wrong in my ajax call? It's pretty straight forward code:

function getActive(){
    if(window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }
    else
    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function()
    {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {   
            var json = JSON.parse(xmlhttp.responseText);
            console.log(json);
        }
    }

    xmlhttp.open("GET", "http://channel.api.livestream.com/1.0/livestatus?channel=huskystarcraft", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send();
}
getActive();

回答1:


You're running into restrictions imposed by the Same Origin Policy. In short, AJAX calls to a different domain are prohibited and will fail - unless explicitly permitted by the remote host.

You need to either use JSONP (mostly applicable to data returned by APIs) or proxy the request through your own server/domain.

CORS would also be an option, but that assumes you having access to the remote server's config.



来源:https://stackoverflow.com/questions/12124538/ajax-access-control-allow-origin-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!