【问题标题】:Access to IBM Weather API with PHP works, but with JS it does not work使用 PHP 访问 IBM Weather API 有效,但使用 JS 则无法访问
【发布时间】:2019-05-29 12:45:52
【问题描述】:

我在我的应用程序中访问 IBM Weather API。

当我尝试使用 PHP 访问时:

$auth = base64_encode("<username>:<password>");
$context = stream_context_create([
"http" => [
    "header" => "Authorization: Basic $auth"
]]);
$homepage = file_get_contents("https://twcservice.eu-gb.mybluemix.net/api/weather/v1/geocode/49.14/15.00/forecast/daily/3day.json?language=en-US&units=m", false, $context );
echo($homepage);

有效。

但是当我尝试使用 Javascript 访问时:

let headers = new Headers();
headers.append("Content-Type", "application/json");
headers.append("Authorization", "Basic " + btoa("<username>" + ":" + "<password>"));
fetch("https://twcservice.eu-gb.mybluemix.net/api/weather/v1/geocode/"+lat.toFixed(2)+"/"+lng.toFixed(2)+"/forecast/daily/3day.json?language=en-US&units=m", {headers: headers})
.then(function(response) {
    console.log(response);
    return response.json();
})
.then(function(json) {
    for(let i = 0; i <= 3; i++) {
        console.log(json['forecasts'][i]['dow']+" - "+json['forecasts'][i]['narrative']);
    }
});

它给了我 CORS 错误消息。

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://twcservice.eu-gb.mybluemix.net/api/weather/v1/geocode/49.14/15.00/forecast/daily/3day.json?language=en-US&units=m. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://*.ibm.com, https://*.ibmcloud.com’).

我不明白为什么。

感谢您的帮助!

如果 IBM Weather API 害怕窃取其内容,为什么它与 PHP 一起工作?

我不明白。

【问题讨论】:

标签: javascript php ibm-cloud


【解决方案1】:

@John Doe

这是 CORS 问题。服务器可以配置为不允许浏览器从不同的域发出请求。如果您不熟悉该主题,关于 CORS 的 Mozilla document 是一本不错的读物。

请注意,只有在通过浏览器执行某些操作时才会遇到 CORS 错误。因此,尝试使用 curl 在终端中重做相同的 API 调用通常仍然有效。让事情变得更加混乱!

您的 PHP 脚本是否通过终端在本地运行?

如果您正在修补,可以使用绕过 CORS 的代理服务,例如 CORS-anywhere。尝试点击 https://cors-anywhere.herokuapp.com/https://twcservice.eu-gb.mybluemix.net 而不是您当前拥有的 API。请注意,这并不意味着任何值得生产的东西。只是想帮助你走得更远一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-04
    • 2018-07-16
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多