如何在Angular 5中使用HttpClient访问响应头? [英] How do I access response headers using HttpClient in Angular 5?

查看:752
本文介绍了如何在Angular 5中使用HttpClient访问响应头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular 5中编写了一个身份验证服务,它使用HttpClient类向我的后端发出POST请求。后端通过发送JWT承载令牌进行响应。

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.

我的请求如下所示:

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?

当我将响应写入控制台时,如上所述,它会显示null。我知道错误不在后端,因为我捕获了流量,后端确实发送了不记名令牌。

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.

非常感谢任何帮助。

推荐答案

要访问完整的响应(不仅仅是响应的主体),您必须传递 observe:'响应您的http请求中的'参数选项。现在,您可以使用 res.headers访问标题

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

文档

这篇关于如何在Angular 5中使用HttpClient访问响应头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆