Reques body is removed from request when accessed (spring-cloud-gateway-mvc)
Describe the bug When I try to read or modify the request body in spring-cloud-gateway-mvc, the body is removed from the request and this exception is thrown:
java.lang.NullPointerException: Cannot invoke "java.util.Map.put(Object, Object)" because the return value of "org.springframework.cloud.gateway.server.mvc.common.MvcUtils.getGatewayAttributes(org.springframework.web.servlet.function.ServerRequest)" is null
I'm using Spring Boot 3.2.2 and cloud 2023.0.0
Sample
I have tried using the BeforeFilterFunctions.modifyRequestBody:
.before(modifyRequestBody(String.class, String.class, MediaType.APPLICATION_JSON_VALUE, (serverRequest, s) -> s))
.. and also a regular filter like this:
.filter((request, next) -> {
byte[] bytes = StreamUtils.copyToByteArray(request.servletRequest().getInputStream());
String requestBody = new String(bytes, StandardCharsets.UTF_8);
LOGGER.info(requestBody);
return next.handle(request);
})
I have used the example from the documentation: ModifyRequestBody Filter
@bsgrd try pass requestBody.
next.handle(requestBody);
I'm unable to reproduce this using this initializr setup
If you'd like us to spend some time investigating, please take the time to provide a complete, minimal, verifiable sample (something that we can unzip attached to this issue or git clone, build, and deploy) that reproduces the problem.
Hi @spencergibb I created a minimal repo with my setup here boot 3.2.2 and cloud 2023.0.0 here gateway I'm gonna test with your initializer setup.
I still can't reproduce with your repository. How are you making the http request?
@spencergibb weird. I'm doing a simple POST request with postman and a random json body.
I also just tried a curl request with same result:
curl -H 'Content-Type: application/json' -d '{ "title":"foo","body":"bar", "id": 1}' -X POST http://localhost:8080
BTW. I should mention that I'm using Java 21. Don't know if that makes a difference. Though i get the same error with java 17.
I see, the path of the uri is not used. See #3292 and #3293
https://github.com/bsgrd/gateway/pull/1
@spencergibb I'm still getting the same error with your fix. I have added a screenshot and the stacktrace.
Using GatewayRouterFunctions.route() was the difference. PR updated.