在從 Angular 前端向 Java 后端發送 REST POST 請求后,后端會接收請求并計算答案。但是,在前端,請求不會顯示在日志中,而是給出了決議錯誤。
有一個來自 Angular 端點的 Rest-Call,即:
getUserID<NonSimpleObject>(nonSimpleObject: NonSimpleObject): Observable<string> {
return this.http.post<string>(this.API_URL '/userId', nonSimpleObject);
}
它在 Java Endpoint 中收到,即:
@POST
@Path("/userId")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String userId(NonSimpleObject nonSimpleObject) {
LOG.info("The searched UserId is: " controller.getUserId(nonSimpleObject);
return controller.getUserId(nonSimpleObject);
}
在后端,日志顯示請求到達并且字串計算正確。字串是字母數字組合,沒有特殊字符。在前端,chrome 日志顯示沒有請求的痕跡,但給出了錯誤
ERROR SyntaxError: Unexpected number in JSON at position 1
at JSON.parse (<anonymous>)
at JsonParser.parse (json-parser.service.ts:64:21)
at CustomJsonParserHttpInterceptor.parseJsonResponse (custom-json-parser-h…nterceptor.ts:47:50)
at custom-json-parser-h…nterceptor.ts:42:64
at map.js:7:37
at OperatorSubscriber._next (OperatorSubscriber.js:13:21)
at OperatorSubscriber.next (Subscriber.js:31:18)
at XMLHttpRequest.onLoad (http.mjs:1840:30)
at _ZoneDelegate.invokeTask (zone.js:406:31)
at Object.onInvokeTask (core.mjs:26341:33)
我希望從后端收到一個好的回應中的字串。關于如何正確處理請求的任何線索?
uj5u.com熱心網友回復:
將字串提供為泛型型別不足以讓 Angular 將其視為字串。Angular 仍然嘗試決議 json 并在此處失敗。請同時設定 responseType 選項。
return this.http.post(this.API_URL '/userId', nonSimpleObject, { responseType: 'text' });
除此之外,您的服務并不正確。它產生一個字串,但你說它產生一個json。還請更改 Produces MediaType:
@Produces(MediaType.TEXT_PLAIN)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/531569.html
