動態

詳情 返回 返回

一次Ajax請求未攜帶cookie問題排查 - 動態 詳情

背景

重寫一個登錄頁面,登錄接口是跨域接口,重寫的頁面登錄成功後進入頁面報錯,原因是請求後台接口未攜帶cookie,但是通過老頁面進行登錄,進入頁面後cookie可以正常攜帶,使用工具對比新老頁面登錄請求,request和response都是一樣。

解決

排除過以下可能性

  • 在代碼中進行cookie刪除
  • 兩個請求頭不一樣導致結果不一樣
  • 系統時間設置錯誤,導致cookie過期

對比過兩邊的ajax請求代碼,確實都是一樣,甚至通過工具逐個字節進行對比也是一樣,最後發現在老頁面一個隱藏的角落有一行這個代碼

$.ajaxSetup({
    dataType: "json",
    async: true,
    xhrFields: {
        withCredentials: true
    },
});

在新頁面加上後問題解決。其中核心的就是withCredentials: true這個配置,經過查詢官方文檔,瞭解到如果跨域請求需要帶上cookie必須設置改參數,官網上是這麼描述的

The XMLHttpRequest.withCredentials property is a boolean value that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-origin requests.

In addition, this flag is also used to indicate when cookies are to be ignored in the response. The default is false. XMLHttpRequest responses from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request. The third-party cookies obtained by setting withCredentials to true will still honor same-origin policy and hence can not be accessed by the requesting script through document.cookie or from response headers.

這裏簡單翻譯下

XMLHttpRequest.withCredentials是一個boolean類型的屬性,用於跨域請求時進行認證,比如cookie,認證頭(authorization headers)或者TLS客户端證書。當請求是同域時該屬性失效。

另外,這個參數也表示是否可以忽略響應cookie,默認是false(也就是忽略cookie),如果沒有設置為true,XMLHttpRequest進行的跨域請求響應的cookie無法設置到該域下,設置withCredentials=true後,同域cookie策略仍然適用於第三方cookie,也就是無法通過 document.cookie獲取響應的cookie。

參考文檔

user avatar erin_5f911ffcecd4e 頭像
點贊 1 用戶, 點贊了這篇動態!
點贊

Add a new 評論

Some HTML is okay.