【问题标题】:Angular 4 HttpClient not able to see headersAngular 4 HttpClient 看不到标头
【发布时间】:2017-09-06 15:58:19
【问题描述】:

我正在尝试访问响应中的标头,docs 说我可以通过在我的 POST 调用的选项中添加 observe: 'response' 来做到这一点。

我已经这样做了,但我能够访问的唯一标头是content-type,我需要访问 3 个自定义标头。代码如下:

public login(username: string, password: string): Observable<LoginResponse> {

  // this just encodes the data
  let data = this.formEncode({
    username: username,
    password: password
  })

  let headers: HttpHeaders = new HttpHeaders()
    .set('Content-Type', 'application/x-www-form-urlencoded')
    // i've also tried below, but it didn't work
    // .set('Access-Control-Expose-Headers', 'X-Custom-Header-Name')

  return this.http.post<LoginResponse>(
    ["www.foobar.com", "users", "login"].join("/"),
    data,
    {
      headers: headers,
      observe: 'response'
    }
  )
  .map((res) => {
    console.log(res)
    console.log(res.headers.getAll('Content-Type'))
    console.log(res.headers.getAll('Set-Cookie'))
    console.log(res.headers.getAll('X-Custom-Header-Name'))
    console.log(res.headers.keys())
    return res.body
  })
}

我知道这里有很多日志,它们都是为了向自己验证content-type 实际上是我在任何这些情况下都可以访问的唯一响应标头。此外,在 Chrome 或 Firefox 开发工具中检查后,响应中有标头。

那么,我在这里做错了什么? Angular 是否只允许您访问某些标头?函数的map 部分中是否没有标头?

在其他新闻中,我尝试这样做的唯一原因是没有正确设置 cookie,但我很确定这不会是 Angular 问题。

编辑:我也尝试使用来自@angular/httpHttp,并得到相同的结果

【问题讨论】:

  • 同样的错误...你能找到解决办法吗?
  • 抱歉迟到了,是的!您需要后端发送 Access-Control-Expose-Headers 标头,其中包含您要访问的标头的值列表!

标签: javascript angular cookies http-headers angular2-http


【解决方案1】:

好的,刚刚找到解决方案,同样的问题。我正在运行 Node/Express 后端,因此在配置 Express 应用程序的中间件时(添加 CORS 支持 & co),我必须添加以下响应标头:

    res.header("access-control-expose-headers",
        +"X-Custom-Header-Name"
        +",Set-Cookie"
        );

完整配置请参见my question

【讨论】:

    猜你喜欢
    • 2018-05-09
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    相关资源
    最近更新 更多