简体   繁体   中英

Angular HttpClient post read headers from empty response

I'm trying to build my authentication on JWT. I'm using Spring filters to achieve that goal, and i'm returning positive (200) response with one header (Authorization) on successfull login. Unfortunately i'm still getting JSON parse problem from my Angular client.

Client code:

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

Response:

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

Error:

message : "Unexpected end of JSON input"

It is working like a charm from REST client like Postman.

I was trying multiple things to get this done:

  • set responseType to text
  • add something to response body (error has changed - it can't parse first letter of new response body)
  • posting without generic HttpResponse object

No luck for now.

responseType is not a http header, but just an options for the http request

You also need to specify observe: response if you want to be able to retrieve the header

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

Try that

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM