簡體   English   中英

Angular HttpClient 從空響應中發布讀取標頭

[英]Angular HttpClient post read headers from empty response

我正在嘗試在 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 對象的發布

暫時沒有運氣。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM