Fetch API 沒有傳送 cookies
- Web
- 25 May, 2022
最近遇到一個案例,用戶明明有登入,但是打 API 時,卻因為沒有登入而噴錯。
在追查 HTTP Request/Response 時,眼尖的同事發現 Request Headers 根本沒有帶上 cookies,所以伺服器因為沒有 session 登入的資訊,所以才會當成 Client 端還沒登入。但奇怪的是 Client 端的網頁明明就是登入狀態。還有另一個線索是用戶的 Chrome 瀏覽器是很舊的版本。
後來透過一些關鍵字追查,追到這個 Stack Overflow 的留言 。原來是因為前端是使用 fetch 打 API,fetch 在舊版跟新版的預設行為不一樣,舊版是預設不帶 cookies(credentials: 'omit'),新版改掉了這個預設行為(credentials: 'same-origin')。所以如果沒有給 credentials 參數,就會使用預設值,造成舊版跟新版瀏覽器行為不一樣。
可以看到 fetch polyfill 這段說明
The default for
credentialswasn’t always the same, though. The following versions of browsers implemented an older version of the fetch specification where the default was “omit”: Firefox 39–60 Chrome 42–67 Safari 10.1–11.1.2 If you target these browsers, it’s advisable to always specifycredentials: 'same-origin'explicitly with all fetch requests instead of relying on the default
fetch不會傳送 cookies,除非你有設定 credentials 的 init option (en-US)。 (Since Aug 25, 2017. The spec changed the default credentials policy tosame-origin. Firefox changed since 61.0b13.)
Make fetch() use “same-origin” credentials by default