最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I access response headers using HttpClient in Angular 5? - Stack Overflow

programmeradmin0浏览0评论

I have written an authentication service in Angular 5 which does a POST request to my backend using the HttpClient class. The backend responds by sending a JWT bearer token.

My request looks like this:

return this.http.post('http://127.0.0.1:8080/api/v1/login', {
  'username': username,
  'password': password
}, {
  headers: new HttpHeaders()
    .set('Content-Type', 'application/json')
})
  .toPromise()
  .then(response => {
    console.log(response);
    return response;
  });

}

How do I access the authorization header of the response?

When I write the response to the console, like above, it says 'null'. I know the error is not in the backend because I captured the traffic and the backend is indeed sending the bearer token.

Any help is very much appreciated.

I have written an authentication service in Angular 5 which does a POST request to my backend using the HttpClient class. The backend responds by sending a JWT bearer token.

My request looks like this:

return this.http.post('http://127.0.0.1:8080/api/v1/login', {
  'username': username,
  'password': password
}, {
  headers: new HttpHeaders()
    .set('Content-Type', 'application/json')
})
  .toPromise()
  .then(response => {
    console.log(response);
    return response;
  });

}

How do I access the authorization header of the response?

When I write the response to the console, like above, it says 'null'. I know the error is not in the backend because I captured the traffic and the backend is indeed sending the bearer token.

Any help is very much appreciated.

Share Improve this question asked Dec 11, 2017 at 13:19 FlorianFlorian 2671 gold badge6 silver badges15 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

To access the full response (not just the body of the response), you must pass the observe: 'response' parameter option in your http request. Now you can access the headers with res.headers

return this.http.post('http://127.0.0.1:8080/api/v1/login', {
        'username': username,
        'password': password
    }, {
        headers: new HttpHeaders()
            .set('Content-Type', 'application/json'),
        observe: 'response'
    })
    .map(res => {
        let myHeader = res.headers.get('my-header');
    });

Docs

发布评论

评论列表(0)

  1. 暂无评论