【问题标题】:Angular HttpClient post read headers from empty responseAngular HttpClient 发布从空响应中读取标头
【发布时间】:2018-07-31 16:22:02
【问题描述】:

我正在尝试在 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 对象的情况下发布

现在运气不好。

【问题讨论】:

    标签: json angular rest jwt


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2019-06-20
      • 2018-01-26
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-25
      • 2018-06-19
      • 2018-01-12
      相关资源
      最近更新 更多