angular - 标题未在 POST 响应中设置

标签 angular go cors

<分区>

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

编辑

在 golang 中设置 set-cookie header 后,在后续请求中添加我的 cookie 在 chrome 中的样子的图片。看起来不像 chrome 自动设置 cookie。

编辑

所以,看起来肯定是浏览器问题。当我用 postman 到达终点时,cookie 肯定已设置。我不一定想在angular中获取cookie,我只是想在浏览器中设置cookie。

enter image description here

我的 Angular 代码:

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

最佳答案

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

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

关于angular - 标题未在 POST 响应中设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52655826/

相关文章:

javascript - Angular 2 Fusion Chart 集成

go - 使用不带命令的 PTY

pointers - 如何编写将数组成员分配给 self 的方法

go-micro 包装器即服务

javascript - 没有 'Access-Control-Allow-Origin' header - 相同域?

javascript - CORS 预检调用不跟在 GET 调用之后

javascript - RxJS zip 在 forkJoin 时不起作用

javascript - Angular:将字符串数组映射到 http get 调用中的枚举值数组

web - 为什么同源策略会阻止读取 GET 响应?

angular - 根据注入(inject)的配置编译模板