我先描述我遇到的情况:
nodejs后端,设置:
app.all('*', function(req, res, next) { console.log("appuse"); res.header("Access-Control-Allow-Origin","*"); res.header("Access-Control-Allow-Headers","Origin, Accept-Language, Accept-Encoding,X-Forwarded-For, Connection, Accept, User-Agent, Host, Referer, Cookie, Content-Type, Cache-Control,*"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("Access-Control-Allow-Credentials",true); res.header("X-Powered-By",' 3.2.1'); res.header("Content-Type", "application/json;charset=utf-8"); next(); });
然后前端ajax请求后端,后端会返回set-cookie
set-cookie:connect.sid=s%3ACOrynUfg9BleXlivy2GWX2n6gYzSnHoP.lX51TZD1YazMhcDJFTdqwPjN6pL7q1dcAhCEElVRGxQ; Path=/; Expires=Sun, 30 Oct 2016 16:15:03 GMT; HttpOnly
像上面那样
服务器如果要发送Cookie,Access-Control-Allow-Origin就不能设为星号,必须指定明确的、与请求网页一致的域名。同时,Cookie依然遵循同源政策,只有用服务器域名设置的Cookie才会上传,其他域名的Cookie并不会上传,且(跨源)原网页代码中的document.cookie也无法读取服务器域名下的Cookie。