[英]Body in serverRequest is null with ServerRequest(Spring Webflux)
I sent the request as below.我发送了如下请求。
curl -d "{""key1"":""value1"", ""key2"":""value2""}" \
-H "Content-Type: application/json" \
-X POST http://localhost:8080/myApi/test
And write route configure as below并编写路由配置如下
RouterFunctions.route()
.path("/myApi", builder -> builder
.POST("/test", handler::test))
.build();
In handler::test,在处理程序::测试中,
public Mono<ServerResponse> test(ServerRequest serverRequest) {
System.out.println(serverRequest.headers());
serverRequest.bodyToMono(String.class).subscribe(System.out::println);
return ServerResponse.ok().body(Mono.just("ok"), String.class);
}
But result is as below.但结果如下。
[Host:"localhost:8080", User-Agent:"curl/7.77.0", Accept:"*/*", Content-Type:"application/json", content-length:"26"]
I add one line to check body is null, and result is as below.我添加一行来检查正文是否为空,结果如下。
System.out.println(serverRequest.bodyToMono(String.class).toProcessor().peek());
null
Is there any way to extract body from ServerRequest
?有什么方法可以从ServerRequest
中提取正文?
You are not supposed to subscribe explicitly to the publisher in WebFlux.您不应该显式订阅 WebFlux 中的发布者。 If you run in debug mode and put breakpoint on return
statement you would see如果您在调试模式下运行并在return
语句上放置断点,您会看到
Caused by: java.lang.IllegalStateException: Only one connection receive subscriber allowed.
In run-time this error is not visible because subscribe
is async and your code exited even before it.在运行时,此错误不可见,因为subscribe
是异步的,并且您的代码甚至在它之前就退出了。
In any case, the correct implementation would look like无论如何,正确的实现看起来像
public Mono<ServerResponse> test(ServerRequest serverRequest) {
return serverRequest.bodyToMono(String.class)
.doOnNext(System.out::println)
.flatMap(body -> ServerResponse.ok()
.body(BodyInserters.fromValue("ok"))
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.