javascript - 为什么我的 10 个请求中有 1 个在浏览器中返回 CORS 错误
问题描述
我目前有一个使用 ajax 请求的脚本XMLHttpRequest()
。该脚本的本质是跟踪某些分析以及它是如何实现的。
- 添加事件侦听器并将数据发送到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){
}
});
- 以下是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){
//...
}
}
- 以下是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.
我真的希望这是解释性的,如果不是,我很乐意提供更多细节。知道为什么会发生这种情况吗?
解决方案
推荐阅读
- android - 社交媒体应用程序中的内容审核
- oauth-2.0 - 使用 PKCE 的授权代码流如何比没有 client_secret 的授权代码流更安全
- java - 消费=“charset=utf-8”不工作春季启动
- machine-learning - 是否可以将牛顿法与图像分类相结合?
- javascript - 检查 div 是否可见
- python - 使用 SSL 访问 Kafka 的 spark 结构化流引发错误
- python - POST 请求只有在通过 httr 感知之前在站点上执行时才有效
- tapestry - Tapestry 不允许动态组件?
- reporting-services - 条形图问题中的SSRS两个类别标签
- javascript - 如何替换 Lodash 的 get 和 set 以在高度复杂的对象中获取和设置属性