Javascript 请求的资源上不存在“Access Control Allow Origin”标头。起源'http://localhost因此不允许访问

Javascript 请求的资源上不存在“Access Control Allow Origin”标头。起源'http://localhost因此不允许访问,javascript,cors,Javascript,Cors,嗨,伙计们,我正试图通过这段代码来绘制一个图表,但我发现请求的资源上没有“accesscontrolalloworigin”头。因此,不允许访问源“XXXX”。我知道有些东西像CORS,但我不知道如何使用它 function get_last_oxygen(location, start_time, end_time) { var xmlHttp = null; var oxy_url = 'http://localhost:8888/' + locati

嗨,伙计们,我正试图通过这段代码来绘制一个图表,但我发现请求的资源上没有“accesscontrolalloworigin”头。因此,不允许访问源“XXXX”。我知道有些东西像CORS,但我不知道如何使用它

function get_last_oxygen(location, start_time, end_time)
    {
        var xmlHttp = null;
        var oxy_url = 'http://localhost:8888/' + location + '/oxygen/1/1/last';
        xmlHttp = new XMLHttpRequest();
        xmlHttp.open( "GET", oxy_url, true );        
        xmlHttp.send( null );
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                var json = JSON.parse(xmlHttp.responseText);
                var oxy = document.getElementById('oxygen');
                oxy.innerHTML = json.oxygen;
                get_oxygen_range(location, start_time, end_time);
                //alert(xmlHttp.status + ' ' + xmlHttp.responseText);
           }
        }
    }

    function get_oxygen_range(location, start_time, end_time) {
        var req_range = null;
        var range_url = 'http://localhost:8888/' + location + '/oxygen/1/1/' + start_time + ':' + end_time;;
        req_range = new XMLHttpRequest();
        req_range.open( "GET", range_url, true );       
        req_range.send( null );
        req_range.onreadystatechange = function() {
            if (req_range.readyState == 4) {
                var measurements = eval(req_range.responseText);
                draw_oxygen_diagram(measurements);
           }
        }
    }

    /* Draw a diagram */
    function draw_oxygen_diagram(data) {
        var container = document.getElementById('container');
        //var data = [[1,10], [2,8], [3,11], [4,7], [5,9]];
        graph = Flotr.draw(container, [data], {
            //shadowSize: 0,
            timeUnit: 'second', 
            yaxis : { 
                max: 20,
                min: 0
            },
            xaxis : {
                mode: 'time'
            }
        });
    }

    function refresh() {
        var now = Math.round(new Date().getTime() / 1000);
        now = 1406906881;
        get_last_oxygen('rauco', now - 86400, now);
        setTimeout(refresh, 5000);
    }

    refresh();

对于PHP服务器,启用CORS所要做的就是添加这一行

header("Access-Control-Allow-Origin: *");
确保在发送任何其他内容之前已设置此选项。这意味着在任何echo语句或html之上。把它放在最上面应该行得通

该网站是一个很好的资源,可用于了解有关CORS的更多信息,以及如何在不同的服务器设置上允许CORS。

请参阅


访问控制允许来源是在服务器的响应上设置的,而不是在客户端请求上设置的,以允许来自不同来源的客户端访问响应。

了解您是否控制了尝试向其发送请求的服务器会有所帮助。您的示例代码显示它是localhost,所以我假设您是这样做的。但是它是什么样的后端呢?我在服务端使用php。你能检查失败的请求并用它发送的http头编辑你的答案吗?我发送了headerAccess Control Allow Origin:*;在php脚本的开始,我得到了相同的错误。