在ExpressJS服务器中,设置响应头的域属性为当前请求的域名:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
res.header("Access-Control-Allow-Headers", "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept");
// 设置cookie域
res.header('Set-Cookie', 'name=value; Domain=' + req.headers.host + '; HttpOnly; SameSite=none; Secure');
next();
});
然后在Angular的http请求配置中设置withCredentials属性:
$http.post(url, data, {
withCredentials: true
}).success(function(data) {
// Do something with the returned data
});