原文地址: 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
}
})
複製代碼