我正在嘗試將字串值從 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"
這是我的代碼:
登錄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.");
}
});
}
uj5u.com熱心網友回復:
該HttpClient自動決議到一個通用的物件,除非你告訴它,否則的回應。您在嘗試決議字串時遇到問題。您需要告訴 HttpClient 您期望的text。設定responseTypeastext并且 HttpClient 知道不要嘗試決議它:
login() {
this.http.post(url, {...}, { responseType: 'text' })
}
請參考檔案:https : //angular.io/guide/http#requesting-non-json-data
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/371902.html
