CORS 跨域 AJAX 與 Cookie 請求
以前使用跨域請求的時候,沒遇到使用 Cookie 的案例,在一般的使用情境下只要將 Access-Control-Allow-Origin、Access-Control-Allow-Methods 及 Access-Control-Allow-Headers 設置好可以正常的跨域請求了。
但當要使用跨域請求修改 Cookie 的內容時,在瀏覽器及伺服器必需要額外設定才能達成目的。
瀏覽器請求
以 axios 的範例來看,必須要在發出請求前帶上 withCredentials: true 的設定,在跨域請求時才會正常發出附帶 Cookie 的 header。
axios.defaults.withCredentials = true;
// or
axios.interceptors.request.use(config => {
config.withCredentials = true;
return config;
});
伺服器回應
而在伺服器回應時也要一並帶上 Access-Control-Allow-Credentials: true 在 header 中,這樣在回應時在 header 中所附帶的 Set-Cookie 才會有作用。
另外要注意的是如果要使用 Access-Control-Allow-Credentials 那麼就不能將 Access-Control-Allow-Origin 設定為 *。
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://example.site
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Credentials: true
Set-Cookie: <cookie-name>=<cookie-value>