XMLHttpRequest.withCredentials 解决跨域请求头无Cookie的问题

查看原文html

XMLHttpRequest.withCredentials  属性是一个Boolean类型,它指示了是否该使用相似cookies,authorization headers(头部受权)或者TLS客户端证书这一类资格证书来建立一个跨站点访问控制(cross-site Access-Control)请求。在同一个站点下使用withCredentials属性是无效的。ajax

此外,这个指示也会被用作响应中cookies 被忽视的标示。默认值是false。json

若是在发送来自其余域的XMLHttpRequest请求以前,未设置withCredentials 为true,那么就不能为它本身的域设置cookie值。而经过设置withCredentials 为true得到的第三方cookies,将会依旧享受同源策略,所以不能被经过document.cookie或者从头部相应请求的脚本等访问。跨域

注: 永远不会影响到同源请求浏览器

Note: 不一样域下的XmlHttpRequest 响应,不论其Access-Control- header 设置什么值,都没法为它自身站点设置cookie值,除非它在请求以前将withCredentials 设为true。安全

 

总结: XMLHttpRequest.withCredentials 能够是用来解决跨域请求时,因为浏览器安全 策略,不会自动携带cookie到服务器的问题。服务器

 

Post请求实例:cookie

 

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请求实例:app

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请求:post

$.ajaxSetup({
    type: "POST",
    data: {},
    dataType: 'json',
    xhrFields: {
       withCredentials: true
    },
    crossDomain: true
})

 

参考:https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/withCredentials

相关文章
相关标签/搜索