跨域請求最常被忽略的細節之一,就是 Cookie。瀏覽器基於安全性預設不會讓跨來源請求夾帶或接收憑證,所以後端明明已經登入,跨域打過去的請求卻像個陌生人。要打通這條路,前端與後端都得各讓一步。
關鍵是 withCredentials 這個屬性,必須在 send() 之前設定:
1 xhr = new XMLHttpRequest();
2 xhr.open("POST", "https://xxxx.com/demo/b/index.php", true);
3 xhr.withCredentials = true; //支持跨域發送cookies
4 xhr.send();
jQuery 沒有直接暴露 withCredentials,要透過 xhrFields 傳進底層的 XHR 物件,同時把 crossDomain 打開:
$.ajax({
type: "POST",
url: "https://xxx.com/api/test",
dataType: 'json',
// 允許攜帶證書
xhrFields: {
withCredentials: true
},
// 允許跨域
crossDomain: true,
success:function(){
},
error:function(){
}
})
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: https://www.xxx.com");
這裡有個最容易踩的雷:Access-Control-Allow-Origin 在允許夾帶憑證時不能寫成 *,必須明確指定來源網域,否則瀏覽器會直接攔下回應。另外,如果請求帶有自訂標頭(例如 Content-Type: application/json),瀏覽器會先發出 preflight 的 OPTIONS 請求,後端要記得放行 Access-Control-Allow-Headers 與 Access-Control-Allow-Methods,並回應正確的狀態碼。