首页 > 解决方案 > 为什么我的 10 个请求中有 1 个在浏览器中返回 CORS 错误

问题描述

我目前有一个使用 ajax 请求的脚本XMLHttpRequest()。该脚本的本质是跟踪某些分析以及它是如何实现的。

  1. 添加事件侦听器并将数据发送到start_tracking_analytics脚本
document.addEventListener('DOMContentLoaded', function(){
try{
    
    //url to send data to
    var url = 'https://subdomain.domain.com/start_tracking_analytics.php?key='+tracker_key;
    
    //host name
    var host = location.protocol + '//' + location.hostname
    
    //send data
    sendAnalytics(url, host);
    
    
        setTimeout(function(){
            setInterval(function(){
                try{
                    sendUpdateAnalytics();
                }catch(e){
                    
                }
            }, 7500);
            
            
        }, 1000);
    
    }catch(e){
        
    }

});
  1. 以下是sendAnalytics函数的实现方式
function sendAnalytics(url, host){
    try{
        var createCORSRequest = function(method, url) {

        var xhr = new XMLHttpRequest();

        if ("withCredentials" in xhr) {
        // Most browsers.
        xhr.open(method, url, true);

        } else if (typeof XDomainRequest != "undefined") {

        // IE8 & IE9
        xhr = new XDomainRequest();
        xhr.open(method, url);

        } else {

        // CORS not supported.
        xhr = null;
        }

        return xhr;

        };


        var method = 'POST';
        var xhr = createCORSRequest(method, url);
        
        xhr.onerror = function() {
        // Error code goes here.
        };

        xhr.send(); 
    }catch(e){
        //...
    }
}
  1. 以下是sendUpdateAnalytics的实现方式。注意:这会每隔一段时间触发
 function sendUpdateAnalytics(){
    try{

        //url to send data to
        var url = 'https://subdomain.domain.com/end_tracking_analytics.php?id='+tracker_session_id; 
        
        //current host
        var host = location.protocol + '//' + location.hostname

        //send the data
        sendData(url, host);
    }catch(e){
        
    }   
}

现在,到后端(响应)脚本。即 - start_tracking_analytics.php && end_tracking_analytics.php

在这两个脚本上,我都设置了这个标题

 //GET variables
$host = $_GET["host"];
$key = $_GET["key"];

//set header for CORS
header("Access-Control-Allow-Origin: $host");
header("Access-Control-Allow-Credentials: true");

//I Do all of my computations here and echo an integer

echo 1;

问题:10 个请求中有 1 个end_tracking_analytics返回 CORS 错误

Access to XMLHttpRequest at 'https://subdomain.domain.com/end_tracking_analytics.php?id=1&host=https://www.hostUrl.com&key=XXXXX' from origin 'https://www.hostUrl.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我真的希望这是解释性的,如果不是,我很乐意提供更多细节。知道为什么会发生这种情况吗?

标签: javascriptphpajax

解决方案


推荐阅读