原文地址: github.com/yinxin630/b…
技术交流: fiora.suisuijiang.com/html
这篇文章将解答如下疑问:ios
不行! 只能向当前域或者更高级域设置cookiegit
例如 client.com
不能向 a.client.com
设置cookie, 而 a.client.com
能够向 client.com
设置cookiegithub
读取cookie状况同上ajax
不管是客户端仍是服务端, 都只能向本身的域或者更高级域设置cookie 例如 client.com
不能向 server.com
设置cookie, 一样 server.com
也不能向 client.com
设置cookieaxios
服务端能够设置 httpOnly: true
, 带有该属性的cookie客户端没法读取跨域
客户端只会带上与请求同域的cookie, 例如 client.com/index.html
会带上 client.com
的cookie, server.com/app.js
会带上 server.com
的cookie, 而且也会带上httpOnly的cookie浏览器
可是, 若是是向服务端的ajax请求, 则不会带上cookie, 详情见第三个问题安全
这个问题与你发起ajax请求的方式有关cookie
fetch在默认状况下, 无论是同域仍是跨域ajax请求都不会带上cookie, 只有当设置了 credentials
时才会带上该ajax请求所在域的cookie, 服务端须要设置响应头 Access-Control-Allow-Credentials: true
, 不然浏览器会由于安全限制而报错, 拿不到响应
axios和jQuery在同域ajax请求时会带上cookie, 跨域请求不会, 跨域请求须要设置 withCredentials
和服务端响应头
By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set). Since Aug 25, 2017. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.
使fetch带上cookie
fetch(url, {
credentials: "include", // include, same-origin, omit
})
复制代码
developer.mozilla.org/en-US/docs/…
//
withCredentials
indicates whether or not cross-site Access-Control requests, should be made using credentials // default: withCredentials: false
使axios带上cookie
axios.get('http://server.com', {withCredentials: true})
复制代码
$.ajax({
method: 'get',
url: 'http://server.com',
xhrFields: {
withCredentials: true
}
})
复制代码