Cookie的設置、讀取以及是否自動攜帶問題

原文地址: github.com/yinxin630/b…
技術交流: fiora.suisuijiang.com/html

這篇文章將解答如下疑問:ios

  1. 能設置或讀取子域的cookie嗎?
  2. 客戶端設置cookie與服務端設置cookie有什麼區別?
  3. 同域/跨域ajax請求到底會不會帶上cookie?

能設置或讀取子域的cookie嗎?

不行! 只能向當前域或者更高級域設置cookiegit

例如 client.com 不能向 a.client.com 設置cookie, 而 a.client.com 能夠向 client.com 設置cookiegithub

讀取cookie狀況同上ajax

客戶端設置cookie與服務端設置cookie有什麼區別?

不管是客戶端仍是服務端, 都只能向本身的域或者更高級域設置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?

這個問題與你發起ajax請求的方式有關cookie

fetch在默認狀況下, 無論是同域仍是跨域ajax請求都不會帶上cookie, 只有當設置了 credentials 時纔會帶上該ajax請求所在域的cookie, 服務端須要設置響應頭 Access-Control-Allow-Credentials: true, 不然瀏覽器會由於安全限制而報錯, 拿不到響應

axios和jQuery在同域ajax請求時會帶上cookie, 跨域請求不會, 跨域請求須要設置 withCredentials 和服務端響應頭

fetch 設置 credentials

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
})
複製代碼
  • include: 跨域ajax帶上cookie
  • same-origin: 僅同域ajax帶上cookie
  • omit: 任何狀況都不帶cookie

developer.mozilla.org/en-US/docs/…

axios 設置 withCredentials

// 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})
複製代碼

github.com/axios/axios…

jQuery 設置 withCredentials

$.ajax({
    method: 'get',
    url: 'http://server.com',
    xhrFields: {
        withCredentials: true
    }
})
複製代碼

yq.aliyun.com/articles/61…

相關文章
相關標籤/搜索