Home > Blockchain >  Return string type from Spring Boot to Angular
Return string type from Spring Boot to Angular

Time:12-02

I am trying to return a string value from Spring Boot to Angular but it gets an HttpErrorResponse when receives the value. I tried using integer type in spring and number type and in this way it works. Can anyone tell me what I'm doing wrong? Thank you.

The HttpErrorResponse that I get in console.log(resp) is:

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: 'OK', url: 'http://localhost:8080/login', ok: false, …}
error: {error: SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: 'user'}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: f}
message: "Http failure during parsing for http://localhost:8080/login"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/login"

This is my code:

login-form.component.ts:

login() {
    let url = 'http://localhost:8080/login';
    this.http.post<string>(url, {
    username: this.model.username,
    password: this.model.password
}).subscribe(resp => {
    console.log(resp);
    switch(resp){
      case "admin": {
        this.router.navigateByUrl('/actions', { state: { username: this.model.username , role:'admin' } });
      break;
      }
      case "user": {
        this.router.navigateByUrl('/actions', { state: { username: this.model.username , role:'user' } });
      break;
      }
      default:
        alert("Authentication failed.");
    } 
    });
  }

CodePudding user response:

The HttpClient automatically parses the the response to a generic object unless you tell it otherwise. You are facing issues as it is trying to parse a string. You need to tell the HttpClient that you expect text. Set the responseType as text and HttpClient knows not to try and parse it:

login() {
  this.http.post(url, {...},  { responseType: 'text' })
}

Please refer to the documentation: https://angular.io/guide/http#requesting-non-json-data

  • Related