此外,這個指示
也會被用做響應中
cookies 被忽視的標示。默認值是false。
如果在發送來自其他域的XMLHttpRequest請求之前,未設置withCredentials
為true,那么就不能為它自己的域設置cookie值。而通過設置withCredentials
為true獲得的第三方cookies,將會依舊享受同源策略,因此不能被通過document.cookie或者從頭部相應請求的腳本等訪問。
注: 永遠不會影響到同源請求
Note: 不同域下的XmlHttpRequest
響應,不論其Access-Control-
header 設置什么值,都無法為它自身站點設置cookie值,除非它在請求之前將withCredentials
設為true。
總結: XMLHttpRequest.withCredentials 可以是用來解決跨域請求時,由於瀏覽器安全 策略,不會自動攜帶cookie到服務器的問題。
Post請求實例:
var xmlhttp if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest() } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP") } xmlhttp.open('POST', 'http://xxx/xxx/script', true) xmlhttp.setRequestHeader('Content-type', 'application/json') xmlhttp.withCredentials = true // 使外部腳本中的post請求頭攜帶當前域的Cookies // 注意:這里不能使用xmlhttp.setRequestHeader('Cookie', document.cookie),這樣設置是不安全的做法 // xmlhttp.setRequestHeader('Cookie', document.cookie) // error xmlhttp.send(JSON.stringify(postData))
Get請求實例:
var xmlhttp if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest() } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP") } xhr.open('GET', 'http://example.com/', true) xhr.withCredentials = true xhr.send(null)
Ajax請求:
$.ajaxSetup({ type: "POST", data: {}, dataType: 'json', xhrFields: { withCredentials: true }, crossDomain: true })
參考:https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/withCredentials