Home > Mobile >  REST answer can't be parsed - how to make it process correctly
REST answer can't be parsed - how to make it process correctly

Time:11-10

After sending a REST POST request from an Angular frontend to a Java backend, the backend recieves the request and computes the answer. However, in the frontend, the request does not show up in the logs, instead a parsing error is given.

There is a Rest-Call from an Angular endpoint, which is:

getUserID<NonSimpleObject>(nonSimpleObject: NonSimpleObject): Observable<string> {
    return this.http.post<string>(this.API_URL   '/userId', nonSimpleObject);
}

it is recieved in the Java Endpoint which is:

@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);
}

In the backend, the log shows that the request arrives and the string is computed correctly. The string is an alphanumeric combination, no special characters. In the frontend, the chrome log shows no trace of the request, but gives the error

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)

I would expect to recieve the String in an ok Response from the backend. Any clues on how to make the request process properly?

CodePudding user response:

Providing the string as generic type is not enough for Angular to treat it as string. Angular still tries to parse json and fails here. Please also set the responseType option.

return this.http.post(this.API_URL   '/userId', nonSimpleObject, { responseType: 'text' });

Besides that your service is not quiet correct. It produces a string, but you say it produces a json. Please also change the Produces MediaType:

 @Produces(MediaType.TEXT_PLAIN)
  • Related