CORS Request with Credential
一般情况下,一个跨域请求不会包含当前页面的用户凭证。一旦一个跨域请求包含了当前页面的用户凭证,那么其就属于 Requests with Credential。
如果要把 Cookie 发到服务器,需要服務器和瀏覽器雙方都同意
What need to be done
Server side
Access-Control-Allow-Credentials: true
Browser side
开发者必须在AJAX请求中設置 withCredentials 属性爲 true,否则,即使服务器同意发送Cookie,浏览器也不会发送。或者,服务器要求设置 Cookie,浏览器也不会处理。
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;如果省略 withCredentials 设置,有的浏览器还是会一起发送 Cookie。这时,可以显式关闭 withCredentials
xhr.withCredentials = false;Notes
- 如果服務器允許瀏覽器發送 Cookie,
Access-Control-Allow-Origin就不能设为星号,必须指定明确的、与请求网页一致的域名。 - Cookie 依然遵循同源政策,只有用服务器域名设置的 Cookie 才会上传,其他域名的 Cookie 并不会上传,且(跨源)原网页代码中的
document.cookie也无法读取服务器域名下的 Cookie。