Angular 如何获取http POST';s的回应';s标题为角8

Angular 如何获取http POST';s的回应';s标题为角8,angular,Angular,所以我有一个帖子,如下所示,我发送一个帖子请求登录,回复为空 -正如预期的那样,这很好,但我需要访问“Authorization”标题 我找不到任何途径进入 const data = {email: "email", password: "password"}; this.http.post(`/login`, data).pipe( tap(resp => { console.log(resp); // it will be an empty string

所以我有一个帖子,如下所示,我发送一个帖子请求登录,回复为空 -正如预期的那样,这很好,但我需要访问“Authorization”标题

我找不到任何途径进入

  const data = {email: "email", password: "password"};

  this.http.post(`/login`, data).pipe(
    tap(resp => {
      console.log(resp); // it will be an empty string
      return resp;
    })).subscribe((resp: any) => {
    console.log(resp.headers.get('Authorization')); // error: Cannot read property 'headers' of null
  });
更新 受TheUnreal答案的启发,我添加了选项

this.http.post(`/login`, data, {observe: 'response'} )...
现在我可以访问一些标题,如“缓存控制”

可能我需要从服务器端表达其余的头


Sam Walpole在评论部分的回答是正确的,这个问题的大部分在他提供的链接上得到了回答-签出。

您可以通过向http方法传递以下选项来获取请求的标题和其他信息:

return this.http.post('YOUR URL', PAYLOAD, {
      observe: 'events'
    })

通过将以下选项传递给http方法,可以获取请求的标题和其他信息:

return this.http.post('YOUR URL', PAYLOAD, {
      observe: 'events'
    })

按照虚幻的建议在帖子中添加选项,但对我来说需要“回复”

this.http.post(`/login`, data, {observe: 'response'} )
在服务器端,需要设置和公开头访问控制允许头访问控制公开头

有点离题,但-可能会帮助某些人-这就是我们的配置在JavaSpring中的样子

configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type", "Access-Control-Allow-Headers", "Origin,Accept", "X-Requested-With", "Content-Type", "Access-Control-Request-Method", "Access-Control-Request-Headers"));
configuration.addExposedHeader("Authorization");

山姆·沃尔波尔(Sam Walpole)在这个问题的评论部分是对的,这个问题的大部分答案都在他提供的链接上——请查看。

按照虚幻的建议在帖子中添加选项,但对我来说需要“回复”

this.http.post(`/login`, data, {observe: 'response'} )
在服务器端,需要设置和公开头访问控制允许头访问控制公开头

有点离题,但-可能会帮助某些人-这就是我们的配置在JavaSpring中的样子

configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type", "Access-Control-Allow-Headers", "Origin,Accept", "X-Requested-With", "Content-Type", "Access-Control-Request-Method", "Access-Control-Request-Headers"));
configuration.addExposedHeader("Authorization");

Sam Walpole在这个问题的评论部分是正确的,这个问题的大部分都在他提供的链接上得到了回答-签出。

您是否尝试过
console.log
仅使用
resp
对象。看到了吗?@Nicolas在第5行中的意思吗?在最后一次
subscribe
callback中没有。看起来这里已经回答了:错误是“无法读取null的属性'headers',所以resp为null。您是否尝试了
console.log
只有
resp
对象。看到有什么了吗?@Nicolas在第5行中的意思了吗?在上一次的
subscribe
callback中没有。看起来这里已经回答了:错误是“无法读取null的属性'headers',所以resp为null。这会取得一些进展,但是resp.headers-属性'headers'在类型'HttpEvent'上不存在。它确实显示了请求头。尝试console.log发出的数据并检查所需内容。这会取得一些进展,但resp.headers-类型“HttpEvent”上不存在属性“headers”,它会显示请求标头。尝试console.log发出的数据并检查所需内容。