0

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.

John Doe
  • 1
  • 1

1 Answers1

0

@John Doe

This is CORS issue. Servers can be configured to not allow browsers to make requests from different domains. The Mozilla document about CORS is a great read if you're unfamiliar with the topic.

Note that you'll only hit CORS errors if you're doing something through a browser. So attempting to redo the same API call in a terminal with curl will often still work. Making things even more confusing!

Was your PHP script run locally, through a terminal?

If you're tinkering around, there are proxy services that bypass CORS, like CORS-anywhere. Try hitting https://cors-anywhere.herokuapp.com/https://twcservice.eu-gb.mybluemix.net instead of the API you currently have. Note that this isn't meant for anything production worthy. Just trying to help you get a little farther along.