2013-10-19 256 views
4

我一直在試圖找到一個解決方案,但沒有發現到目前爲止工作。所以我試着用角HTTP請求到天氣的API,但我不斷收到這樣的響應:訪問控制允許來源和Angular.js

Origin http://mydomain.com is not allowed by Access-Control-Allow-Origin. 

我試過到目前爲止:

  1. 添加此line to my app config

    delete $ httpProvider.defaults.headers.common ['X-Requested-With'];

  2. 我已經試過多個版本的的角度,都具有相同的結果

  3. 添加此我.htacces

    頭添加訪問控制允許來源「*」

  4. 使用PHP添加標頭

  5. 嘗試GET請求的不同URL

    (甚至不同的API,相同的結果)

  6. 使用jQuery的HTTP請求而不是角的,同樣的結果...

我的代碼

 $http({ 
      method: 'GET', 
      url: 'https://api.forecast.io/forecast/myapikey/52.370216,4.895168' 
     }). 
     success(function(response) { 
      console.log('succes'); 
      console.log(response); 
     }). 
     error(function(response) { 
      console.log('failed'); 
      console.log(response); 
     }); 

無這些解決方案似乎工作,我一直在使用Angular,並且通常會添加delete $httpProvider.defaults.headers.common['X-Requested-With'];將解決問題

我完全失去了這裏,任何幫助表示讚賞,謝謝!

+0

您是否嘗試過使用JSONP? – subZero

+0

@subzero - 他不運行forecast.io,所以他不能讓他們發送JSONP響應。 – Quentin

+0

@Quentin https://developer.forecast.io/docs/v2#options他們確實提供支持jsonp – subZero

回答

1

您可以使用JSONP:

$http.jsonp('https://api.forecast.io/forecast/myapikey/52.370216,4.895168' +'?callback=JSON_CALLBACK')...

鏈接:Make Jsonp Requests With AngularJs

+0

這是優越的答案 - 不需要服務器代理。 – rushkeldon

0

豪爾赫有正確的想法。 $ http.jasonp是最簡單的路線。

以下是使用$ q返回延期承諾的示例。

function getForecast(lat, lon){ 
    var deferred = $q.defer(); 
    var apiKey = 'my-actual-api-key-here'; 
    var url = 'https://api.forecast.io/forecast/' + apiKey + '/' + lat + ',' + lon + '?callback=JSON_CALLBACK'; 

    $http.jsonp(url) 
     .success(function forecastReceived(forecastData, status, headers, config) { 
      deferred.resolve(forecastData); 
     }) 
     .error(function forecastFailed(errorData, status, headers, config) { 
      deferred.reject(errorData); 
     }); 

    return deferred.promise; 
} 

,或者您可以使用(像我一樣)restangular,但你必須先進行設定:

function isDataGood(forecastData){ 
    var isGood = false; 
    // test data here 
    // isGood = true; 
    return isGood; 
} 

var apiKey = 'my-actual-api-key-here'; 
Restangular.setBaseUrl('https://api.forecast.io/'); 
Restangular.setJsonp(true); 
Restangular.setDefaultRequestParams('jsonp', { callback: 'JSON_CALLBACK' }); 
var API = Restangular.one('forecast/' + apiKey); 

function getForecast(lat, lon){ 
    var deferred = $q.defer(); 

    function failed(error){ 
     // TODO : retry logic here 
     deferred.reject(error); 
    } 

    API 
     .one(lat + ',' + lon) 
     .get() 
     .then(
      function forecastReceived(forecastData) { 
       if(isDataGood(forecastData)){ 
        deferred.resolve(forecastData); 
       } else { 
        failed({ msg : 'ERROR : received bad data' }); 
       } 
      }, 
      function forecastFailed(error) { 
       failed(error); 
      }); 

    return deferred.promise; 
} 
+0

注意:很多人擁有'RestangularProvider'而不僅僅是'Restangular' - 但它相當於同樣的東西。 – rushkeldon