亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Ajax跨域登錄請求未攜帶cookie錯誤解決

 更新時間:2023年10月31日 10:22:16   作者:DQuery  
這篇文章主要為大家介紹了Ajax跨域登錄請求未攜帶cookie錯誤解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

背景

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

解決

排除過以下可能性

  • 在代碼中進行cookie刪除
  • 兩個請求頭不一樣導(dǎo)致結(jié)果不一樣
  • 系統(tǒng)時間設(shè)置錯誤,導(dǎo)致cookie過期

對比過兩邊的ajax請求代碼,確實都是一樣,甚至通過工具逐個字節(jié)進行對比也是一樣,最后發(fā)現(xiàn)在老頁面一個隱藏的角落有一行這個代碼

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

新頁面加上后問題解決

其中核心的就是withCredentials: true這個配置,經(jīng)過查詢官方文檔,了解到如果跨域請求需要帶上cookie必須設(shè)置改參數(shù),官網(wǎng)上是這么描述的

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類型的屬性,用于跨域請求時進行認(rèn)證,比如cookie,認(rèn)證頭(authorization headers)或者TLS客戶端證書。當(dāng)請求是同域時該屬性失效。

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

參考文檔

以上就是Ajax跨域登錄問題請求未攜帶cookie錯誤解決的詳細(xì)內(nèi)容,更多關(guān)于Ajax請求未攜帶cookie的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論