Search code examples
angularspring-bootspring-mvcangular-httpclient

How To Fix SyntaxError: Unexpected token b in JSON at position 0


I want to read an e-mail address as a string from my backend using Spring MVC. However, when I try to read it using Angular's HttpClient, I get the following error:

SyntaxError: Unexpected token b in JSON at position 0 at JSON.parse

This is a screenshot of the error displayed within the console:

Screenshot of console

This is the code I'm using in Angular to read the response:

public findEmail(username: string): Observable<string> {
  let params = new HttpParams();
  params = params.append('username', username);
  return this.httpClient.get<string>(this.baseUrl + '/findEmail', {params});
}

And this is the code of the Spring controller that provides the response:

@GetMapping(value = "/findEmail", params = { "username" })
public String findEmail(@RequestParam String username) {
    return utilisateursService.findEmail(username);
}

Solution

  • You don't have a JSON response, your response is plaintext (an e-mail address) as can be seen by the error in the first screenshot.

    Spring by default uses the StringHttpMessageConverter when you return a string, which means that it will simply return the string and use text/plain, for example foo@example.com.

    This means that the response won't be valid JSON. To turn it into a valid JSON, you would need to have additional quotes, for example "foo@example.com".

    The solution is to:

    1. Either return a JSON response from your backend. This can be done by wrapping the response (the e-mail) within a class. As soon as you return objects, Jackson will serialize them as JSON. For example:

      @GetMapping
      public User getUser() {
          // Response will be { "email": "foo@example.com" }
          return new User("foo@example.com");
      }
      
    2. Or to tell HttpClient to interprete the response as plain text by using the responseType option. This is also mentioned by the documentation:

      this.httpClient.get<string>('http://example.org', {responseType: 'text'});
      
    3. Or to remove StringHttpMessageConverter from the existing converters. This will cause the conversion to fallback on Jackson, which will convert the response into a valid JSON string. The solution to do this can be seen in this answer.

    4. Alternatively, you could just add additional quotes to your response. For example by returning "\"foo@example.com\"" within your Spring controller.