Angular HttpClient从空响应中读取标头

时间:2018-02-21 07:05:55

标签: json angular rest jwt

我正在尝试在JWT上构建我的身份验证。我使用Spring过滤器来实现这一目标,并且我在成功登录时使用一个标头(授权)返回肯定(200)响应。不幸的是,我仍然从我的Angular客户端获得JSON解析问题。

客户代码:

this.http.post<HttpResponse<void>>(EndPoint.LOGIN,
  {'username': username, 'password': password } ,
  {'headers' : new HttpHeaders ({'Content-Type' : 'application/json', 'responseType': 'text'})})
.subscribe(response => console.log(response.headers.get('Authorization')))
  ;

响应:

authorization →Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJHZXJhbHQiLCJleHAiOjE1MjAwNTk4MzN9.813r4QmVgrnrsm4HwZID1M56hD42PLe0BvbCu-bQoQWSnxllOE0iAjS-fc-BI8R8eGGE0WPSSL0OaKxz2lxDjA
content-length →0

错误:

message : "Unexpected end of JSON input"

它的工作方式类似于Postman等REST客户端的魅力。

我正在尝试多种方法来完成这项工作:

  • 将responseType设置为文本
  • 向响应正文添加内容(错误已更改 - 它无法解析新响应正文的第一个字母)
  • 发布没有通用的HttpResponse对象

现在没有运气。

1 个答案:

答案 0 :(得分:2)

responseType不是http标头,而只是http请求的选项

如果您希望能够检索标题

,还需要指定observe:response

https://angular.io/guide/http#reading-the-full-response

试试

this.http.post(EndPoint.LOGIN,
  {'username': username, 'password': password } ,
  {'headers' : new HttpHeaders ({'Content-Type' : 'application/json'}), 'responseType': 'text', observe:'response'})
.subscribe((response : any) => console.log(response.headers.get('Authorization')))
  ;