未在POST响应上设置标头

时间:2018-10-04 22:04:36

标签: angular go cors

我已经用Go编写了一个POST API端点,并且在Golang响应中设置了一个名为Set-Cookie的标头。我已经设置了cors,并且该呼叫返回了正确的值。问题在于响应中的标头为空。如果我查看“网络”选项卡,它说我返回的Set-Cookie标头具有我期望的值,它只是一个角度,为空(请参见response.headers和我的网络的console.log屏幕截图)标签)。

编辑

在golang中设置了Set-Cookie标头后,在随后的请求中添加一张我的cookie在chrome中的图片。看起来不像chrome自动设置cookie。

编辑

因此,这绝对是浏览器问题。当我用邮递员到达终点时,cookie肯定已设置好。我不一定要使cookie呈角度,我只想在浏览器中设置cookie。

enter image description here

我的角度代码:

login(user): Subscription {
    return this.http
      .post(`${SERVICE_URL}/login`, user, {
        observe: 'response',
        headers: new HttpHeaders({'Content-Type': 'application/json'})
      })
      .subscribe((response: HttpResponse<any>) => {
       console.log(response.headers);
      }, (response) => {
        this._user$.next(null);
        console.log(response);
      });
  }

使用rs / cors在golang服务器中设置我的cors设置

c := cors.New(cors.Options{
        AllowedMethods: []string{"GET","POST", "PUT", "OPTIONS"},
        AllowedOrigins: []string{"http://localhost:4200", "localhost:4200"},
        AllowedHeaders: []string{"X-Requested-With", "Content-Type", "Authorization", "Set-Cookie"},
        ExposedHeaders: []string{"Set-Cookie"},
        AllowCredentials: true,
    })

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:0)

浏览器(看起来像chrome devtools)将为您处理Cookie 。如果您在devtools的应用程序选项卡中查找,则可以找到cookie。如果您需要在Angular中获取该标头的值,建议您使用其他标头。浏览器不会拦截的一种。最好将标头命名为x-my-header

Angular中没有用于处理cookie的api,但是那里有支持ngx-cookie-service的软件包

答案 1 :(得分:0)

有趣的事实:我在响应中设置了AllowCredentials: true,但是我没有在Angular请求中设置它。 chrome在两个地方都需要它来设置cookie。

相关问题