我试图将一个字符串值从 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/