withCredentials 屬性

什麼是 credentials

credentials,即用戶憑證,是指 cookie、HTTP身份驗證和TLS客戶端證書。須要注意的是,它不涉及代理身份驗證或源標頭。跨域

XMLHttpRequest 的 withCredentials 屬性

  • 默認值爲false。在獲取同域資源時設置 withCredentials 沒有影響。
  • true:在跨域請求時,會攜帶用戶憑證
  • false:在跨域請求時,不會攜帶用戶憑證;返回的 response 裏也會忽略 cookie

規範文檔中描述,它在特定狀況下會報錯cookie

throws an InvalidStateError exception if state is not unsent or opened, or if the send() flag is set.spa

這裏的 state 是指 XMLHttpRequest 的 readyState 屬性,咱們來簡單回顧一下相關內容。代理

狀態 狀態碼 說明
unsent 0 初始化 XMLHttpRequest 對象以後
opened 1 open() 方法成功執行以後
headers received 2 全部的重定向都找到了,全部的 response 的響應頭都收到了
loading 3 response's body 正在接收
done 4 數據接收完成或者出錯了

send() flag 是在調用 send() 方法以後設置的。當 state 爲 done 時,銷燬 send() flagcode

IE 10

原來,在IE10環境下,withCredentials 屬性必須在open方法成功執行以後,send執行以前設置才能夠,不然會報錯。若是open方法執行失敗了,設置 withCredentials 屬性依然會報錯。相關演示以下圖所示對象

圖片描述

詳情參看 XMLHttpRequest 文檔 https://xhr.spec.whatwg.org/圖片

相關文章
相關標籤/搜索