【问题标题】:Cookie and Single Page Application configurationCookie 和单页应用程序配置
【发布时间】:2018-06-18 09:37:14
【问题描述】:
我有一个在 localhost:4200 运行的 Angular 应用程序
我的 API 后端运行在 localhost:8080
API 后端提供设置 cookie 的身份验证端点:
localhost:4200 -> localhost:8080 POST /auth?creds=mycreds
响应 204 Set-Cookie: mycookie=myvalue; HttpOnly
以下从 localhost:4200 到 localhost:8080 的 XHR 请求没有将 cookie 传输到后端。我不明白为什么。
【问题讨论】:
标签:
angular
cookies
single-page-application
【解决方案1】:
由于安全问题,Cookie 从不跨域传输。如果请求的域相同,则 Cookie 存储始终附加到请求。但是您可以从浏览器获取您的 cookie 并手动添加您的响应。使用以下代码:
postData(dataToBePosted) {
return this.http.post("someurl", {header: new HttpHeaders("cookieName", this.getCookie("cookieName")});
}
private getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
希望对你有帮助