【问题标题】:Headers aren't being set on POST response [duplicate]未在 POST 响应中设置标头 [重复]
【发布时间】:2019-03-10 09:12:00
【问题描述】:

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

编辑

在 golang 中设置 Set-Cookie 标头后,在后续请求中添加我的 cookie 在 chrome 中的外观图片。看起来 chrome 不会自动设置 cookie。

编辑

所以,这绝对是浏览器的问题。当我用邮递员到达端点时,肯定设置了 cookie。我不一定要获取角度的cookie,我只想在浏览器中设置cookie。

我的角码:

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);
      });
  }

我在 golang 服务器中使用 rs/cors 的 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,
    })

【问题讨论】:

  • 在您的 Angular .post(...) 调用中,尝试设置“withCredentials: true”。 (顺便说一句,反对票不是来自我……)
  • cookie 被标记为 HttpOnly 使得 JavaScript 无法访问它。 developer.mozilla.org/en-US/docs/Web/HTTP/Headers/…
  • 我只是想让它为浏览器设置cookie,我不一定需要用angular来做。

标签: angular go cors


【解决方案1】:

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

Angular 中没有用于操作 cookie 的 api,但有一些包可以启用它,例如“ngx-cookie-service”

【讨论】:

  • Chrome 似乎没有设置 cookie。我点击了设置 Set-Cookie 标头的端点,然后点击了另一个输出请求 cookie 值的端点,它是空的。我会在问题中发布一张图片。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2018-06-24
    • 2017-08-21
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 2019-03-21
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多