Search code examples
angularspring-boothttpangular-httpclient

Angular 8/httpclient error response for plain/text, cannot parse response


On the browser it shows this error. I am testing Springboot and am trying to implement a bearer authentication. I am returning the token as text.

error: Object { error: SyntaxError, text: "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJpdm9uZXRlYnJ1bmFAYm9sLmNvbS5iciIsImV4cCI6MTU3NzUzODgzMH0.oUMmxd65XJtdfLKmlhbczp3-u1LIGzfzCla0RyKeIy0PKlq4upxd_7NtxfMspFCtpniuqsiwpGjpH_yWTrDbqg" }
​
headers: {…}
​​
lazyInit: function lazyInit()
​​
lazyUpdate: null
​​
normalizedNames: Map(0)
​​
<prototype>: Object { … }
​
message: "Http failure during parsing for http://localhost:8080/login"
​
name: "HttpErrorResponse"error: Object { error: SyntaxError, text: "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJpdm9uZXRlYnJ1bmFAYm9sLmNvbS5iciIsImV4cCI6MTU3NzUzODgzMH0.oUMmxd65XJtdfLKmlhbczp3-u1LIGzfzCla0RyKeIy0PKlq4upxd_7NtxfMspFCtpniuqsiwpGjpH_yWTrDbqg" }
​
headers: {…}
​​
lazyInit: function lazyInit()
​​
lazyUpdate: null
​​
normalizedNames: Map(0)
​​
<prototype>: Object { … }
​
message: "Http failure during parsing for http://localhost:8080/login"
​
name: "HttpErrorResponse"

My service is set up like this:

 logar (credenciais: Credenciais): Observable<any> {


    const httpOptions = {
      headers: new HttpHeaders({'Content-Type': 'application/json',  accept: 'text/plain'})
    };
    return this.http.post("http://localhost:8080/login", credenciais, httpOptions);
  }

I am not an expert in http headers but I found every strange that the response from Spring doesn't have a content-type. Here is the response:

HTTP/1.1 200 
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:4200
Vary: Origin
Access-Control-Allow-Methods: *
Access-Control-Allow-Headers: Origin, X-Requested-With, Authorization, Content-Type, Accept, X-CSRF-TOKEN
Access-Control-Max-Age: 3600
Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJpdm9uZXRlYnJ1bmFAYm9sLmNvbS5iciIsImV4cCI6MTU3NzUzOTc5NH0.-YOzULQnPD6aDIoxzqOQbxbCOpZChJni2FKCazLr-0jTe6ExwwAT8L9V4m5qUoJ68jDz71aE2lrbSbmWPciWCQ
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Length: 182
Date: Wed, 18 Dec 2019 13:29:54 GMT
Keep-Alive: timeout=60
Connection: keep-alive

I can see the response from the server on the browser console. The problem is parsing the response. The reponse is available but I cannot manipulate it. How can I remody this?


Solution

  • Try adding the { responseType: 'text' } to the list of http options.

    const httpOptions = {
      headers: new HttpHeaders({'Content-Type': 'application/json',  accept: 'text/plain'})
      responseType: 'text'
    };