I create an API to get the country of the user from Spring boot. The code snippets are displayed below.
SearchRepository.java
@Query("SELECT u.country FROM Users u WHERE u.email = :email")
String findCountryByEmail(@Param("email") String email);
Controller.java
@Autowired
private SearchRepository user;
@GetMapping("/country/{email}")
public String getCountry(@PathVariable("email") String email) {
return user.findCountryByEmail(email);
}
This API returns the country as a string. I want to display this country on my angular frontend. I created the following codes in angular to achieve this task.
DataService.ts
getCountry(email: string) {
return this.http.get<string>(`${API_URL}/country/${email}`);
}
profile.ts
getCountry(myEmail: string) {
this.service.getCountry(myEmail)
.subscribe(
data => this.country = data
);
}
I used the above getcountry method inside the ngOninit to initialize the country of the user when loading the profile. But the country field remained empty and when I checked the console I got the following error.
core.js:6014 ERROR
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/country/[email protected]", ok: false, …}
error:
error: SyntaxError: Unexpected token E in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:34481:51) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:3626:31) at Object.onInvokeTask (http://localhost:4200/vendor.js:97626:33) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:3625:60) at Zone.runTask (http://localhost:4200/polyfills.js:3403:47) at ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:3700:34) at invokeTask (http://localhost:4200/polyfills.js:4838:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:4875:21)
text: "England"
__proto__: Object
headers: HttpHeaders
lazyInit: () => {…}
lazyUpdate: null
normalizedNames: Map(0) {}
__proto__: Object
message: "Http failure during parsing for http://localhost:8080/country/[email protected]"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/country/[email protected]"
__proto__: HttpResponseBase
The backend API is working perfectly and the error is in frontend. I want to get only the country value from the backend as a string. Can someone point me out what's wrong with my approach, please?
UPDATE
As per the answers received I changed the return type of java controller from string to ResponseEntity as follows.
@Autowired
private SearchRepository user;
@GetMapping("/country/{email}")
public ResponseEntity<String> getCountry(@PathVariable("email") String email) {
return ResponseEntity.ok(user.findCountryByEmail(email));
}
But the error remains the same. As I understand the error caused because of a syntax error of the JSON response. But I couldn't figure out it. Can anyone point me out this?