2015-10-05 34 views
2

我對所有這些相同來源政策的事情都很瘋狂。當API不允許訪問控制 - 允許來源時怎麼辦

當我嘗試做了谷歌地圖API的請求我沒有問題:

var jsonData = $.ajax({ 
     url:"http://maps.googleapis.com/maps/api/geocode/json?address=", 
     dataType:"json", 
     async:true, 
     success: function(json){...} 
} 

我認爲,這是因爲谷歌地圖API允許訪問控制允許來源。但是,當我嘗試使用openls.geog.uni-heidelberg.de API我得到的跨域錯誤:

var xmlData = $.ajax({ 
       type: "GET", 
       url:"http://openls.geog.uni-heidelberg.de/route?" 
       //dataType:"jsonp xml", 
       dataType: "xml", 
       async:true, 
       crossDomain : true, 
       success: function(xml){...} 
} 

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost ' is therefore not allowed access.

人認爲我不明白的是,如果openls API不允許跨-origin爲什麼可以直接從我的瀏覽器做請求剛剛鍵入URL,如:

http://openls.geog.uni-heidelberg.de/route?start=9.256506,49.240011&end=8.72083,49.7606&via=&lang=de&distunit=KM&routepref=Bicycle&weighting=Shortest&avoidAreas=&useTMC=false&noMotorways=false&noTollways=false&noUnpavedroads=false&noSteps=false&noFerries=false&instructions=false

但我可以使用jQuery無法做到。我也嘗試過jsonp解決方案,但它不適用於xml。

關於發生了什麼的一些想法?

+0

嘗試將'dataType'更改爲'jsonp' - 我想在當前的例子中可以使用JSONP而不是CORS。 – vitozev

+0

@unixarmy鑑於它正在返回XML我不認爲JSONP會起作用。 –

+0

啊,對不起,我沒有注意到。你是對的! :) – vitozev

回答

2

我奮鬥了太長引起的兩個項目的本地運行(角App和Web服務的Node.js)

看哪短期簡單的解決方案的相互作用CORS問題:Chrome的插件AllowControlAllowOrigin。

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

剛剛從紅色開關單選按鈕爲綠色,並沒有更多的被禁止的請求,錯誤或警告! 我希望它能與你的API協同工作,當然這不是一個永久的解決方案,但這是一個很好的方法,可以避免在那些煩人的經常性問題上浪費時間。

相關問題