I access to IBM Weather API in my application.
When I try to access with 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);
It works.
But when I try to access with 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']);
}
});
It gives me the CORS error message.
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’).
I don't understand why.
Thanks for help!
If the IBM Weather API is scared about stealing its content, why does it work with PHP?
I don't get it.