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?

2
  • JSON is malformed. Probably not a JSON at all Commented Sep 12, 2018 at 20:19
  • So, how am I supposed to handle this differently on the client side? Commented Sep 12, 2018 at 20:42

3 Answers 3

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'})
Sign up to request clarification or add additional context in comments.

3 Comments

So, how am I supposed to handle this differently on the client side?
Try http.get(url, {responseType: text'}
After reading this answer I found it in documentation, too: angular.io/guide/http#requesting-non-json-data
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.

1 Comment

I tried many ways and this is the only one that worked.
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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.