【发布时间】:2021-03-23 23:48:20
【问题描述】:
我编写了一个 JS 脚本,它使用来自 http API 的数据(GET 请求的端点:http://api.open-notify.org/iss-now.json)。我打算在托管在 github 页面上的页面中使用它(它使用 https 协议)。
现在它已上线,我在控制台中看到,由于混合活动内容错误,无法在浏览器中使用此数据:Blocked loading mixed active content “http://api.open-notify.org/iss-now.json”。
我无法应用 this 解决方案,因为我没有使用 server.js 文件(我的内容由 github 提供)。我想尝试this other 解决方案,但它需要在另一个选项卡中打开适配器页面,这是不可行的。
我正在尝试this workaround 但https://cors-anywhere.herokuapp.com/http://api.open-notify.org/iss-now.json 返回错误(缺少必需的请求标头。必须指定以下之一:来源,x-requested-with)。如果有人知道如何向 loadJSON 方法添加标头,请告诉我,我在其文档中找不到任何内容。我对fetch 的语法不太放心,所以当我尝试时:
var response = fetch("https://cors-anywhere.herokuapp.com/http://api.open-notify.org/iss-now.json", {
headers: {
Origin: window.location.protocol + '//' + window.location.host
}
});
if (response.ok) { // if HTTP-status is 200-299
// get the response body (the method explained below)
var json = response.json();
return(json);
} else {
alert("HTTP-Error: " + response.status);
}
我添加了“origin”标题,却发现自己有一个
跨域请求被阻止:同源策略不允许读取 远程资源在 https://cors-anywhere.herokuapp.com/http://api.open-notify.org/iss-now.json。 (原因:缺少 CORS 标头“Access-Control-Allow-Origin”) 据我了解,这只能在服务器端更正。 cors-anywhere 的 github 页面鼓励在您自己的脚本中实现他们的解决方案,方法是添加以下 sn-p:
(function() {
var cors_api_host = 'cors-anywhere.herokuapp.com';
var cors_api_url = 'https://' + cors_api_host + '/';
var slice = [].slice;
var origin = window.location.protocol + '//' + window.location.host;
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
var args = slice.call(arguments);
var targetOrigin = /^https?:\/\/([^\/]+)/i.exec(args[1]);
if (targetOrigin && targetOrigin[0].toLowerCase() !== origin &&
targetOrigin[1] !== cors_api_host) {
args[1] = cors_api_url + args[1];
}
return open.apply(this, args);
};
})();
但我不知道如何实现它,我暂时还没有成功地将它集成到我的代码中。
我的代码现在有点乱,但我可以给你看这么多:
// global functions for the Tracker sample
function getData() {
// var promise = fetch("http://api.open-notify.org/iss-now.json");
loadJSON("http://api.open-notify.org/iss-now.json", gotData, 'jsonp');
}
function gotData(data) {
background(img)
displaySample()
// this will allow you to see the raw data live in your browser console
//console.log(data.iss_position.latitude);
//console.log(data.iss_position.longitude);
posX = (parseFloat(data.iss_position.latitude * latConst) + translateX)
posY = (parseFloat(data.iss_position.longitude * lonConst)* -1 + translateY)
console.log(posX);
console.log(posY);
fill(250, 50, 50, 90);
ellipse(posX, posY, 10, 10);
}
function draw() {
// case tracker
if (selectedSample === 1) {
translateX = boxSizeWidth / 2;
translateY = boxSizeHeight / 2;
latConst = boxSizeWidth / 360;
lonConst = boxSizeHeight / 180;
if (t === 0) {
getData()
}
}
我还尝试找到一个提供相同数据(国际空间站的实时纬度和经度)的 https API,但我目前似乎找不到任何数据,无论如何找到解决方法会很有趣。
【问题讨论】:
标签: javascript api cors p5.js mixed-content