rest - Angular 6:HttpErrorResponse SyntaxError:JSON 中的意外標記 s
我正在發佈一個請求,我應該會收到一個 'success' 字串作為回應。但我收到了 HttpResponseError,詳情如下面圖片所示。
採購訂單服務
postPurchaseOrderCustom(purchaseOrderCustom: PurchaseOrderSaveCustom) {
const url = `${this.localUrl}purchaseOrderCustom`;
return this.http.post<String>(url, purchaseOrderCustom, {headers: this.header})
.pipe(
catchError(this.handleError('postPurchaseOrderCustom', 'I am an error'))
);
}
採購訂單組件
this.purchaseOrderService.postPurchaseOrderCustom(purchaseOrderCustom).subscribe( response => {
console.log("Testing", response);
},
error => {
console.error('errorMsg',error );
}
我做這件事的方式跟文件中說明的方法一樣。請指出我哪裡做錯了。
答案#1
這與你的 API 回應類型有關,success 不是有效的 JSON 格式,預設情況下 HttpClient 預期的是 JSON 回應類型,並稍後嘗試解析它。你可以透過將回應類型設置為 text 來解決這個問題,像這樣
return this.http.post<String>(
url,
purchaseOrderCustom,
{ headers: this.header, responseType: 'text' }
)
.pipe(
catchError(this.handleError('postPurchaseOrderCustom', 'I am an error')
));
答案#2
正如已經有人說過的,這完全與您伺服器的回應有關。
就我而言,我有一個 Spring Boot 應用程式返回了這個:
return new ResponseEntity<>("Your SSN was generated successfully", HttpStatus.OK);
而這是我在 Angular 端得到的回應:
{error: SyntaxError: Unexpected token Y in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHtt…, text: "Your SSN was registered successfully."}
所以我所做的是在我的 Spring Boot 應用程式中創建一個自訂的 CustomHttpResponse 類,然後將控制器中的代碼改成這樣:
...
CustomHttpResponse customHttpResponse = new CustomHttpResponse();
customHttpResponse.setMessage("Your SSN was registered successfully.");
customHttpResponse.setStatus(HttpStatus.OK.value());
return new ResponseEntity<>(new Gson().toJson(customHttpResponse),
HttpStatus.OK);
}
現在我得到這個:
{message: "Your SSN was registered successfully.", status: 200}
message: "Your SSN was registered successfully."
status: 200
本質上,當 Angular 預期收到 JSON 卻收到其他內容時,就會發生此錯誤

