Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

444
Visualizações
Return string type from Spring Boot to Angular

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.");
    } 
    });
  }
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda