2017-07-24 54 views
0

我試圖訪問谷歌根據指導線在這裏映射時區API:https://developers.google.com/maps/documentation/timezone/intro訪問谷歌地圖時區API問題

如果我把網址:「https://maps.googleapis.com/maps/api/timezone/json?key=MY_API_KEY&location=43.7029682,-79.62146709999999&timestamp=1500669556」在瀏覽器中,我可以得到預期的結果爲:

{ 
    "dstOffset" : 3600, 
    "rawOffset" : -18000, 
    "status" : "OK", 
    "timeZoneId" : "America/Toronto", 
    "timeZoneName" : "Eastern Daylight Time" 
} 

然後,我試圖在angularJs中訪問此API。所以我用我平時用它來訪問其他API如下的方式:

var googleGeoTimeDefrred; 
var getGoogleGeoTime = function(position) { 
    googleGeoTimeDefrred = $q.defer(); 
    var userId = store.get("profile").user_id; 
    $http({ 
     method:"GET", 
     url: "https://maps.googleapis.com/maps/api/timezone/json?key=MY_API_KEY&location=43.7029682,-79.62146709999999&timestamp=1500669556" 
    }).then(function (success) { 
     googleGeoTimeDefrred.resolve(success); 
    }, function (error) { 
     googleGeoTimeDefrred.reject(status); 
    }); 
    return googleGeoTimeDefrred.promise; 
}; 

但我得到的錯誤:

XMLHttpRequest cannot load https://maps.googleapis.com/maps/api/timezone/json?key=MY_API_KEY&location=43.7029682,-79.62146709999999&timestamp=1500669556. Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers in preflight response. 

我是新來angularJs。我沒有問題使用上述方式訪問其他API(不是來自谷歌)。有誰知道是什麼原因導致這個問題?

謝謝。

回答

0

我嘗試了不同的方法,我發現在stackoverflow上。如:

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

Request header field is not allowed by Access-Control-Allow-Headers with $http

最後,我通過添加以下到system.webServer下我的Web.config文件中解決的問題。

<httpProtocol> 
    <customHeaders> 
    <add name = "Access-Control-Allow-Origin" value="http://localhost"/> 
    <add name = "Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Cache-Control"/> 
    <add name = "Access-Control-Allow-Credentials" value="true"/> 
    <add name = "Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/> 
                     
    </customHeaders> 
                 
</httpProtocol> 

希望這可以幫助其他人誰遇到這個問題。