简体   繁体   中英

Can't get Boolean as BodyParameter from RouterFunction<ServerResponse> with BodyToMono

I'm trying to get a boolean parameter from an Angular 6 app and Spring can't handle it. I got the following error:

org.springframework.web.server.UnsupportedMediaTypeStatusException: 415 UNSUPPORTED_MEDIA_TYPE "Content type 'text/plain;charset=UTF-8' not supported for bodyType=java.lang.Boolean"

That's my front end code:

  updateConfirmationDate(reportInfo: number, isItTrue: boolean): Observable<Boolean> {
    const url = this.url;
    return this.httpClient.patch(url, isItTrue).pipe(first(), catchError(err => console.log(err)));
  }

And that's how i handle it on back:

Router:

    public RouterFunction<ServerResponse> router() {
        return RouterFunctions.route()
                .path(apiPrefix, builder -> builder
                        .PATCH("/patchBooleanEndpoint", diagnosticHandler::updateBooleanEndpoint)
                     )
                )
                .build();
    }

Handle:

    @NonNull
public Mono<ServerResponse> updateMyBoolean(ServerRequest request) {
    final Long id = Long.parseLong(request.pathVariable("id"));

    return request.bodyToMono(Boolean.class)
            .flatMap(myBoolean -> service.updateBooleanById(id, myBoolean))
            .flatMap(savedBoolean ->
                    status(HttpStatus.OK)
                            .contentType(MediaType.APPLICATION_JSON)
                            .body(Mono.just(savedBoolean), Boolean.class));
}

Thank you very much and have a nice day

You have to set content-Type to 'application/json' when you call the backend server from your Angular app.

something like

const headers = new HttpHeaders()
    .set("Content-Type", "application/json");

And then set it to your patch request.

Based on the stack trace, the fronted call the backend server with content-Type = 'text/plain;charset=UTF-8' so it (the backend server) fails to parse the request body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM