2012-01-14 82 views
47

我有一個跨域AJAX GET獲得預先成功,但餅乾不會附加到GET請求。 當用戶單擊登錄按鈕時,會發出一條POST來登錄該用戶,該用戶可以正常跨域進行工作。 JavaScript的是:CORS請求 - 爲什麼cookie未發送?

 $.ajax(signin_url, { 
      type: "POST", 
      contentType: "application/json; charset=utf-8", 
      data: JSON.stringify(credentials), 
      success: function(data, status, xhr) { 
       signInSuccess(); 
      }, 
      error: function(xhr, status, error) { 
       signInFailure(); 
      }, 
      beforeSend: function(xhr) { 
       xhr.withCredentials = true 
      } 
     }); 

的響應頭包括一個cookie:

Set-Cookie:user_token=snippysnipsnip; path=/; expires=Wed, 14-Jan-2032 16:16:49 GMT 

如果登錄成功,一個JavaScript GET請求以獲取當前用戶的詳細信息:

function signInSuccess() { 
    $.ajax(current_user_url, { 
     type: "GET", 
     contentType: "application/json; charset=utf-8", 
     success: function(data, status, xhr) { 
      displayWelcomeMessage(); 
     }, 
     beforeSend: function(xhr) { 
      xhr.withCredentials = true; 
     } 
    }); 
} 

從Chrome的OPTIONS請求返回的CORS相關標頭爲:

Access-Control-Allow-Credentials:true 
Access-Control-Allow-Headers:X-Requested-With, X-Prototype-Version, Content-Type, Origin, Allow 
Access-Control-Allow-Methods:POST, GET, OPTIONS 
Access-Control-Allow-Origin:http://192.168.0.5 
Access-Control-Max-Age:1728000 

但是,GET請求上不發送cookie。

回答

65

的問題是與jQuery的要求 - 它似乎自1.5 withCredentials應指定爲:

 $.ajax("http://localhost:3000/users/current", { 
      type: "GET", 
      contentType: "application/json; charset=utf-8", 
      success: function(data, status, xhr) { 
       hideAllContent(); 
       $("#sign_out_menu_item").show(); 
       $("#sign_in_menu_item").hide(); 
       $("#welcome").text("Welcome " + data["username"] + "!"); 
       $("#welcome").show(); 
      }, 
      xhrFields: { 
       withCredentials: true 
      }, 
      crossDomain: true 
     }); 
+6

有在得到這個工作花了4個小時。希望我以前看過這篇文章。謝謝! – ChrisRich 2015-01-21 06:03:58

+0

PUT/OPTIONS似乎不能以相同的方式工作。爲什麼cookie會發送GET/POST而不是PUT預檢選項請求? – 2015-04-30 15:07:06

+2

本地主機上的Cookies不工作(未設置)。如果您需要在本地使用Cookie,請改爲使用基於ip的域名(例如'127.0.0.1')。 – Dziamid 2015-05-29 11:06:38