2016-10-06 31 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 –

相關問題