1

I'm making the following call to the Dark Sky API:

axios({
      url: 'https://api.darksky.net/forecast/[my key]/37.8267,-122.4233',
      timeout: 20000,
      method: 'get',
      responseType: 'json'
    })
    .then(function(r) {
      console.log(r);
    })
    .catch(function(r){
      console.log(r);
    });

And I'm getting this error:

XMLHttpRequest cannot load https://api.darksky.net/forecast/[my key]/37.8267,-122.4233. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

I've tried adding a config as the second parameter to the call, and setting config to be:

var config = {
    headers: {'Access-Control-Allow-Origin': '*'}
};

But, I'm pretty sure that has to be done on the server side? Also tried making the response jsonp to see if that would fix it, and still nothing. I also tried using simply the fetch() API, but that didn't work, either.

If it makes any difference, I'm making this call in a React app. How can I just get the JSON and move on with my project?

Cassidy
  • 3,328
  • 5
  • 39
  • 76

2 Answers2

0

Try out JSONP. Not as secure as CORS but functional:

            $.get( weatherAPI, function( weather ) {
                console.log(weather);
            }, 'jsonp');
Radar Hill
  • 81
  • 3
0

Obviously, DarkSky.net did apply this cross-domain policy intentionally to save you - the developer some money: https://darksky.net/dev/docs/faq#cross-origin

We take security very seriously at Dark Sky. As a security precaution we have disabled cross-origin resource sharing (CORS) on our servers.

Your API call includes your secret API key as part of the request. If you were to make API calls from client-facing code, anyone could extract and use your API key, which would result in a bill that you'd have to pay. We disable CORS to help keep your API secret key a secret.

To prevent API key abuse, you should set up a proxy server to make calls to our API behind the scenes. Then you can provide forecasts to your clients without exposing your API key.

So, it seems, the way to go is to either choose a PHP script or some other form of server-side proxy service.

Community
  • 1
  • 1
  • I can query their API no problem with jQuery. But I came across this becasue I thought other libraries should let me do it as well. https://gist.github.com/adampatterson/f7b087c3c7ad13f19008efeef17a2b69 – Adam Patterson May 11 '17 at 19:41