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:
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);
}
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:
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");
}
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'});
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.
Alternatively, you could just add additional quotes to your response. For example by returning "\"foo@example.com\""
within your Spring controller.