Spring Boot API Gateway携带请求体返回400 Bad Request,无请求体端点正常
Spring Boot API Gateway 带请求体请求返回400问题排查与解决
问题现象
发送包含请求体的请求至Spring Boot API Gateway时,网关直接返回400 Bad Request,未将请求转发至后端服务;无需请求体的端点可正常工作。
排查与解决方向
1. 验证请求方法合规性
确认请求方法与后端接口要求一致:GET请求携带请求体不符合HTTP标准,网关会直接拦截并返回400,需改用POST/PUT等支持请求体的方法。
2. 确保请求体可重复读取
Spring Cloud Gateway默认处理请求体时可能存在读取后无法再次转发的问题,添加全局过滤器缓存请求体:
@Bean public GlobalFilter requestBodyCacheFilter() { return (exchange, chain) -> { ServerHttpRequest request = exchange.getRequest(); // 非表单类型的非空请求体进行缓存 if (request.getHeaders().getContentLength() > 0 && !request.getHeaders().getContentType().isCompatibleWith(MediaType.MULTIPART_FORM_DATA)) { return DataBufferUtils.join(request.getBody()) .map(dataBuffer -> { DataBufferUtils.retain(dataBuffer); return exchange.mutate() .request(new ServerHttpRequestDecorator(request) { @Override public Flux<DataBuffer> getBody() { return Flux.just(dataBuffer); } }).build(); }) .flatMap(chain::filter); } return chain.filter(exchange); }; }
3. 检查请求体格式与后端校验
- 确认请求体JSON格式正确,无语法错误,且符合后端接口的参数约束(如必填字段、数据类型)。
- 开启网关调试日志,查看具体错误细节:
logging: level: org.springframework.cloud.gateway: DEBUG org.springframework.http.server.reactive: DEBUG org.springframework.web.reactive: DEBUG
4. 校验跨域配置
若存在跨域场景,确保网关CORS配置允许携带请求体:
spring: cloud: gateway: globalcors: cors-configurations: '[/**]': allowed-origins: "*" allowed-methods: ["GET", "POST", "PUT", "DELETE"] allowed-headers: "*" allow-credentials: true
内容的提问来源于stack exchange,提问作者Aref
相关产品推荐
相关产品推荐

