XMLHttpRequest cannot load – Origin is not allowed by Access-Control-Allow-Origin.

今天使用appmobi的模擬器調試程序的時候,發現使用jquery的getJson方法調用的內容不顯示。(前面使用appCan的模擬器也有這個問題)
查看後臺報錯:
XMLHttpRequest cannot load http://192.168.103.xx:8085/xxx/TestJsonInfo?value=1. Origin http://localhost:58888 is not allowed by Access-Control-Allow-Origin.

解決辦法:
1.頁面請求的是自己寫的一個servelet,加入response.setHeader("Access-Control-Allow-Origin", "*");
2.請求頁面html,加入<meta http-equiv="Access-Control-Allow-Origin" content="*">

以下內容爲轉載
原始頁面:http://blog.sharechiwai.com/2012/04/xmlhttprequest-cannot-load-origin-is-not-allowed-by-access-control-allow-origin/

今天在一個主題是使用主辦單位的API 的Hack Event上 出現了一個趣事…
就是其中一個API 出現了很多的問題…
相信他們是沒有真正的測試過便開放了這一個Beta給開發人員使用..
其中一個問題是他們提供的SandBox URL 不是正確的
另一個問題是使用者/開發者的帳戶…和API Key 很像沒有和SandBox 連結在一起..
當使用使用者/開發者的帳 的API Key 時不能使用這個API…
最後..我只可以使用Sample Code上的URL…

誰不知..當我準備好..瞭解他的FunctionData Structure時…
正開始開發時..又出現一個很嚴重的問題
就是當我當試使用JQuery 的 $.getJSON 功能來 取資料時…
頁面沒有顯示任何資料..
當我使用Google Chrome的 Debugging Console 看看有沒有任何錯誤信息時
發現以下的錯誤資訊
XMLHttpRequest cannot load http://api.europeandirectories.com/search.json?country=NL&what=pizza&where=Amsterdam&userid=portaluser&apikey=8f989d50f277c5ec3b9e890d497be820. Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin.

error:  Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin.

聽說這是一個和Cross-domain 想關的的問題…
API 的Provider 需要在他們的Server/Service上更改一些設定來解決這個問題

另一個解決方法是使用JSONP …
但是如果API 是沒有Implement JSONP的時候..你便沒有辦法了…

很可惜這個API 真是在一個很Beta的 Stage…所以還是沒有JSONP 的…

幸好最後有一個負責這個 API的開發人員 介紹了一個
暫時的解決方法:
就是啟動 Google Chrome時 停用他的網路安全 設定

大家可以按”開始/Start” -> “執行/Run
之後輸入以下文字
chrome.exe –disable-web-security
run command chrome.exe --disable-web-security to bypass Origin is not allowed by Access-Control-Allow-Origin
之後按”確定/OK

當我再次嘗試這個Test Page時 便可以顯示資料了

Hope you find it useful.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章