2016-12-01 71 views
0

我一直運行到錯誤No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.Axios公司沒有訪問控制允許來源

我知道,這是一個經常被問到的問題在網絡上,但我在這裏沒有看到有幫助的答案上比其他計算器使用JSONP的解決方法。

我的代碼是

componentDidMount() { 
    if (navigator.geolocation){ 
     function success(position) { 
     var latitude = position.coords.latitude; 
     var longitude = position.coords.longitude; 
     axios.get(`https://api.darksky.net/forecast/apikey/`+latitude+`,`+longitude+`?units=auto`) 
     .then(result => { 
      this.setState({ 
      daily: result.data.daily.data, 
      loading: false, 
      error: null 
      }); 
     }) 
      .catch(err => { 
      // Something went wrong. Save the error in state and re-render. 
      this.setState({ 
       loading: false, 
       error: err 
      }); 
      }); 
     }; 
     function error() { 
     console.log('geolocation error') 
     }; 
     navigator.geolocation.getCurrentPosition(success.bind(this), error); 
    } 
    } 
+0

如果愚蠢目標答案上的答案都不能解決您的問題,則可能無法解決。您必須遵循CORS策略,在沒有XHR(又名jsonp)的情況下發出請求,或者從服務器發出請求。 –

回答

-1

這是ajax調用瀏覽器限制,只有三個位置可用的選項。

  1. 如果您擁有所請求的服務器,則可以將Access-Control-Allow-Origin添加爲您的應用程序域。

否則這兩個是唯一的選擇。

  1. 使用JSONP作爲使用回調的響應格式n進程。

  2. 您可以將服務器端代理用於例如。您可以撥打nginx的或Apache的配置圖「somerequest」路徑,要使用即外部域yourapplication.com/somerequest,api.darksky.net

0

如果您在訪問服務器端應用程序,請按照Mohamed Jahaber Sadiq提供的第一個答案

如果目的只是爲了查看結果,您可以使用「Allow-Control-Allow-Origin:*」chrome插件,默認情況下會將標頭添加到所有通過chrome處理的響應。

相關問題