2016-10-06 30 views
1

我做以下调用黑暗的天空API:axios GET请求的资源上存在“否”Access-Control-Allow-Origin'标头“。

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); 
    }); 

而且我得到这个错误:

的XMLHttpRequest无法加载https://api.darksky.net/forecast/[my键] /37.8267,-122.4233。请求的资源上没有“Access-Control-Allow-Origin”标题。因此'Origin'http://localhost:3000'不允许访问。

我试着加入了config作为第二个参数的号召,并设置config是:

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

但是,我敢肯定,必须要在服务器端做了什么?还尝试做出回应jsonp看看是否可以解决它,但仍然没有。我也尝试使用简单的fetch() API,但是这也不起作用。

如果它有什么不同,我在React应用程序中进行此调用。我如何才能获得JSON并继续进行我的项目?

+0

是的,这必须在服务器端允许。这是一个浏览器策略,所以如果你通过你自己的服务器(express/node等)进行代理,那么你将可以在没有CORS的情况下进行呼叫。 –

+0

@DavinTryon,那么如何编辑我的代码来工作并给我JSON? –

+0

要求api.dark.sky的所有者支持Ajax。 –

回答

0

试用JSONP。没有安全的CORS但功能:

  $.get(weatherAPI, function(weather) { 
       console.log(weather); 
      }, 'jsonp'); 
0

显然,DarkSky.net并有意将此跨域策略来拯救你 - 开发者一些钱: 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.

所以,似乎,要走的路是选择一个PHP脚本或其他形式的服务器端代理服务。

+0

我可以查询他们的API没有问题与jQuery。但是,我认为这是因为我认为其他图书馆也应该让我这样做。 https://gist.github.com/adampatterson/f7b087c3c7ad13f19008efeef17a2b69 –

相关问题