angular - 将字符串类型从 Spring Boot 返回到 Angular

标签 angular spring-boot rest http post

我试图将一个字符串值从 Spring Boot 返回到 Angular,但在收到该值时它会收到 HttpErrorResponse。 我尝试在 spring 中使用整数类型和数字类型,这样它就可以工作。 谁能告诉我我做错了什么?谢谢。

我在 console.log(resp) 中得到的 HttpErrorResponse 是:

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"

这是我的代码:

登录表单.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.");
    } 
    });
  }

最佳答案

HttpClient 自动解析对通用对象的响应,除非您另有说明。您在尝试解析字符串时遇到问题。您需要告诉 HttpClient 您需要文本。将 responseType 设置为 text 并且 HttpClient 知道不要尝试解析它:

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

请引用文档:https://angular.io/guide/http#requesting-non-json-data

关于angular - 将字符串类型从 Spring Boot 返回到 Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70188989/

相关文章:

java - 如何在 Spring Boot 中手动验证用户身份?

android - LinkedIn登录后如何获取用户数据

angular - 我应该如何在 Angular 8 中为 @ViewChild 使用新的静态选项?

java - IBM WebSphere 部署 Angular 5 应用程序并在刷新时获取 404

java - @EmbeddId 在 hibernate 中抛出 org.hibernate.id.IdentifierGenerationException : null id generated while using . save() 函数

spring-boot - Thymeleaf 如何为 Google Chart 输出对象数组

angular - 为 Angular 为 5 的 Angular Material datePicker 设置默认值

javascript - 每个 Angular 组件的范围类名称和脚本

spring - 每个事务的单个对象实例

asp.net-mvc - 如何使用mvc连接Restful Service