Angular: HttpErrorResponse :"Http failure during parsing for..." - a String returning successfully from server
Asked Answered
W

3

6

Spring-boot RESTful server side; a testing method that will return a string:

@RequestMapping(value = "test", method = RequestMethod.GET)
    public ResponseEntity<String> test(HttpServletRequest req, HttpServletResponse resp) {
        try {
            return new ResponseEntity<String>("Test has worked, biatch!", HttpStatus.OK);
        } catch (Exception e) {
            System.err.println("## EXCEPTION: " + e.getMessage());
            return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }

from Postman- everything works perfectly fine and I get the String returned parsed correctly from JSON.

However, when trying the same from my Angular client-side, I keep getting an HttpErrorResponse object generated.

  public url: string = "http://localhost:8080/theater/admin/test";
  constructor(private as: AdminService, private http: HttpClient) { }

  ngOnInit() {
  }

  getTest() {
    this.as.getTest()
      .subscribe(data => console.log(data), // this should happen on success
        error => console.log(error));  // this should happen on error
  }

funny enough, it contains the String returned from the server, and I can access it with error.text on the subscribe function. the Error object on console:

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/theater/admin/test", ok: false, …}
error
:
{error: SyntaxError: Unexpected token T in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttp…, text: "Test has worked, biatch!"}
headers
:
HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message
:
"Http failure during parsing for http://localhost:8080/theater/admin/test"
name
:
"HttpErrorResponse"
ok
:
false
status
:
200
statusText
:
"OK"
url
:
"http://localhost:8080/theater/admin/test"
__proto__
:
HttpResponseBase

This probably has to do with parsing the JSON object returning from the server, containing the String. however, returning objects, collections and whatever else- works totally fine- .subscribe() parses whatever objects I get from the server correctly, or if the server had an exception occurred, the returned HttpStatus correctly invokes an HttpErrorResponse on the client side.

So, what's up with Strings mis-firing like that? I'm always getting an HttpErrorResponse, no matter what. am I doing something wrong here?

Witness answered 12/9, 2018 at 20:14 Comment(2)
JSON is malformed. Probably not a JSON at allSemipalatinsk
So, how am I supposed to handle this differently on the client side?Witness
S
14

Test has worked, biatch!

This is not a JSON. Thus parsing error.

This probably has to do with parsing the JSON object returning from the server, containing the String. however, returning objects, collections and whatever else- works totally fine- .subscribe()

Well it worked for POJOs besause those are JSON encoded. Here you have plain String

To get response as string instead of object, do something like

 http.get(url, {responseType: 'text'})
Semipalatinsk answered 12/9, 2018 at 20:21 Comment(3)
So, how am I supposed to handle this differently on the client side?Witness
Try http.get(url, {responseType: text'}Semipalatinsk
After reading this answer I found it in documentation, too: angular.io/guide/http#requesting-non-json-dataSpeller
A
13

Try something like this -

{ responseType: 'text' as 'json' }

I was facing the same issue with HttpClient in Angular 7, resolved using the above setup.

The problem is when you use a return type on the get or post or any method from httpClient like this-

this.http.get<FooClass>(url)

It assumes that the response type is JSON and thus it expects a JSON object in response. Setting the response type as 'text' as 'json' will force text response.

Armchair answered 7/2, 2019 at 8:50 Comment(1)
I tried many ways and this is the only one that worked.Olivo
J
0

I solved this issue by using a JsonObject to properly build the JSON String that is then inserted into the ResponseEntity:

@PostMapping(...)
public ResponseEntity handler(HttpServletRequest req, HttpServletResponse resp) {
  JsonObjectBuilder builder = Json.createObjectBuilder();
  builder.add("text", "Hello World!");
  JsonObject json = builder.build();

  return new ResponseEntity<>(json.toString(), HttpStatus.OK);
}

Juniper answered 21/3, 2019 at 21:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.