2015-06-04 25 views
1

我想通過Mapbox使用Surface API來分析兩個給定點之間的地形。我正在接受這兩點的座標並向API發送一個AJAX調用,但我被卡在臭名昭着的CORS問題中。如何從mapbox解決Surface API中的CORS問題?

首先我想使用由Mapbox本身在它的例子中提供的網址:

$('#runTerrainAnalysis').on('click', function(e){ 
    var url = 'https://api.tiles.mapbox.com/v4/surface/mapbox.mapbox-terrain-v1.json?layer=contour&fields=ele&points=-112.084004,36.05322;-112.083914,36.053573;-112.083965,36.053845&access_token=pk.eyJ1Ijoicm9oYW4wNzkzIiwiYSI6IjhFeGVzVzgifQ.MQBzoHJmjH19bXDW0b8nKQ'; 
    $.ajax({ 
     url: url, 
     method: 'GET', 
     success: function(response){ 
      console.log(response); 
     }, 
     error: function(response){ 
      console.log(response); 
     } 
    }); 
}); 

跨來源請求阻止:同源策略不允許讀 遠程資源在 https://api.tiles.mapbox.com/v4/surface/mapbox.mapbox-terrain-v1.json?layer=contour&fields=ele&points=-112.084004,36.05322;-112.083914,36.053573;-112.083965,36.053845&access_token=pk.eyJ1Ijoicm9oYW4wNzkzIiwiYSI6IjhFeGVzVzgifQ.MQBzoHJmjH19bXDW0b8nKQ 。 (原因:缺少CORS頭'Access-Control-Allow-Origin')。

這是怎麼工作的?

+0

嘗試包括:'跨域:TRUE' –

回答

0

我們可以使用JSONP發送跨域AJAX請求。下面是一個簡單的JSONP請求:

$.ajax({ 
    url : url, 
    dataType:"jsonp", 
}); 

Source

工作就像一個魅力。 :)

0

Mapbox API支持cross-origin requests沒有域限制,所以它必須與jquery相關。

嘗試包括crossDomain: true

$.ajax({ 
    url: url, 
    crossDomain: true, 
    method: 'GET', 
+0

號隱而不宣」不幸的是工作。 – Rohan

+0

我已經用angularjs在這裏(用你的數據)做了一個測試,返回值是** _「Feature not enabled。請閱讀https://www.mapbox.com/blog/introducing-the-surface-api 獲取更多信息。「_ ** –

+0

是的,公鑰是不正確的,但即使如此,我應該得到你得到的錯誤。我也嘗試了正確的公鑰。我已經使用Postman REST客戶端嘗試了它,我可以看到'Access-Control-Allow-Origin→*'頭部返回,這意味着它已啓用,結果也如預期。但是,當我嘗試使用我的jQuery時,它不起作用。 :( – Rohan

0

看起來好像您還沒有要求訪問Surface API(它目前處於私人測試版)。這:

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script> 
<script> 
    var url = 'https://api.tiles.mapbox.com/v4/surface/mapbox.mapbox-terrain-v1.json?layer=contour&fields=ele&points=-112.084004,36.05322;-112.083914,36.053573;-112.083965,36.053845&access_token=pk.eyJ1Ijoicm9oYW4wNzkzIiwiYSI6IjhFeGVzVzgifQ.MQBzoHJmjH19bXDW0b8nKQ'; 
    $.ajax({ 
     url: url, 
     method: 'GET', 
     success: function(response){ 
      console.log(response); 
     }, 
     error: function(response){ 
      console.log(response); 
     } 
    }); 
</script> 

返回預期的結果:

{"message":"Feature not enabled. Please read https://www.mapbox.com/blog/introducing-the-surface-api for more information."} 

您可以要求在該頁面的底部訪問:https://www.mapbox.com/blog/introducing-the-surface-api/