Search code examples
javascriptangularcookieshttp-headersangular2-http

Angular 4 HttpClient not able to see headers


I'm trying to get access to the headers in the response, which the docs say I can do by adding observe: 'response' to the options on my POST call.

I've done that, but the only header I am able to access is content-type, and I need access to 3 custom headers. Here's the code:

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

I know there are a lot of logs here, and they're all to verify to myself that content-type is, in fact, the only response header that I have access to in any of these situations. Also, upon inspection in Chrome or Firefox dev tools, there are headers on the response.

So, what am I doing wrong here? Are there only certain headers that Angular lets you access? Are headers not available in the map part of the function?

In other news, the only reason I'm trying to do this at all is because the cookies are not being set properly, but I'm pretty sure that wouldn't be an Angular issue.

Edit: I've also attempted to use Http from @angular/http, and get the same results


Solution

  • Ok, just found the solution, same issue here. I'm running a Node/Express backend, so when configuring the Express app's middlewares (adding CORS support & co), I have to add the following response header:

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

    See my question for full config.