简体   繁体   English

如何在Angular 5中使用HttpClient访问响应标头?

[英]How do I access response headers using HttpClient in Angular 5?

I have written an authentication service in Angular 5 which does a POST request to my backend using the HttpClient class. 我已经在Angular 5中编写了一个身份验证服务,该服务使用HttpClient类向我的后端发出POST请求。 The backend responds by sending a JWT bearer token. 后端通过发送JWT承载令牌进行响应。

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'. 当我像上面那样将响应写到控制台时,它显示为“ 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. 很感谢任何形式的帮助。

To access the full response (not just the body of the response), you must pass the observe: 'response' parameter option in your http request. 要访问完整的响应(而不仅仅是响应的主体),必须在http请求中传递observe: 'response'参数选项。 Now you can access the headers with res.headers 现在您可以使用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 文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM