angular - 浏览器不保存 cookie

标签 angular cookies

我的问题是:浏览器不保存 Set-Cookie header 中的 cookie。
我有在我的桌面上本地部署的前端 (Angular2)。暂存服务器上的后端,因此交互是通过 CORS 进行的。

我在带有 Set-Cookie header 的请求中得到了什么:

HTTP/1.1 200 OK
Date: Tue, 08 Aug 2017 11:00:03 GMT
Server: .....
Access-Control-Allow-Origin: http://localhost:4200
Access-Control-Allow-Credentials: true
Content-Type: application/json
Content-Length: 39
Set-Cookie: session=.........; Path=/
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive

在得到上述答案后,我将发送以下请求:

GET /api/..... HTTP/1.1
Host: ...{some url}...
Connection: keep-alive
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
Content-Type: application/json
Accept: application/json, text/plain, */*
withCredentials: true
Referer: http://localhost:4200/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,ru;q=0.6,uk;q=0.4

如您所见,那里没有 cookie。此外,我无法在外部应用程序(Chrome 插件)、JS 控制台和 Application 部分的网络控制台中看到它们。所以cookies肯定不会被浏览器保存。

我的问题是:问题出在哪里?是我的 header 有问题/其他什么,还是 header 的后端问题?哪里有问题?

关于重复的答案 - 如您所见,我尝试了在其他主题中可以找到的答案,但它们没有解决我的问题。

最佳答案

偶然发现了答案。那些会遇到同样问题的人, 检查您是否以正确的方式定义 header 。
原因是 withCredentials header 及其在 Angular 中的定义。要正确设置它,您应该按以下方式进行:

let options = new RequestOptions();
options.withCredentials = true;

使用这种语法应该没问题。

关于angular - 浏览器不保存 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45568234/

相关文章:

javascript - 如何从 index.html 中的动态脚本中删除内容

c# - 如何设置asp.net Identity cookies过期时间

java - 微服务中的 session 管理

android - NativeScript 模式在 ios 上全屏显示

angular - node_modules/ang-jsoneditor/jsoneditor/jsoneditor.component.d.ts(13,9) 中的错误

angular - 无效值错误 : in property origin: not a string; and not a LatLng or LatLngLiteral: not an Object; and not an Object

angularjs - 组件内部的 Angular2 表单验证

javascript - 无法删除 _fbp Cookie

json - 第三方 cookie - 从其他域读取

javascript - 曲奇饼。 CORS。如果我提交表单而不使用preventDefault(),浏览器不会设置cookie;