2011-12-20 69 views
4

我正在研究一個小的Chrome擴展,它將調用Remember the Milk API。谷歌有一個使用Flikr API的good example,我將它用作我的擴展的基礎。他們的例子在我的瀏覽器(Linux上最新的Chrome)上完美運行。從Chrome擴展中的JavaScript調用網站API時出現跨域錯誤

當我換出記住牛奶API方法名稱和API密鑰,不過,我發現了以下錯誤:

XMLHttpRequest cannot load http://api.rememberthemilk.com/services/rest/?method=rtm.test.echo&api_key=xxxxxxxxxxxxxxxxxxxxxx&name=Test%20task. 
Origin chrome-extension://lifnmciajdfhj is not allowed by Access-Control-Allow-Origin. 

我的代碼如下所示:

var req = new XMLHttpRequest(); 
    req.open(
      "GET", 
      "http://api.rememberthemilk.com/services/rest/?" + 
      "method=rtm.test.echo&" + 
      "api_key=xxxxxxxxxxxxxxxxxxxxxxxxxx&" + 
      "name=Test%20task", 
      true); 
    req.onload = onResponseReceived; 
    req.send(null); 

    function onResponseReceived() { 
     console.log("It worked."); 
    } 

任何建議?

回答

7

And ......像往常一樣,在幾分鐘內發佈在這裏。問題是manifest.json文件,它最初具有Flikr API的權限。我已經更新了它們以指向記住牛奶,但顯然您需要卸載並重新安裝擴展才能重新註冊權限。

谷歌有一個很好的教程處理XHR in extensions

這是更新的manifest.json。也許它會對別人有幫助。

{ 
     "name": "Remember the Milk", 
     "version": "1.0", 
     "description": "A Remember the Milk extension.", 
     "browser_action": { 
      "default_icon": "rtm.png", 
      "popup": "popup.html" 
     }, 
     "permissions": [ 
      "http://*.rememberthemilk.com/", 
      "https://*.rememberthemilk.com/" 
     ] 
    } 
0

確保其從服務器端允許頭

//header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); 
// or 
header("Access-Control-Allow-Origin: *"); 
header("Access-Control-Allow-Credentials: true"); 
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); 
header('Access-Control-Max-Age: 1000'); 
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description'); 

而且還要檢查您的域在WWW或非www redirction開。

相關問題