React调用SpringBoot POST接口出现CORS请求失败问题求解
解决SpringBoot API POST接口CORS请求失败问题
排查方向及解决方案
检查POST接口的请求映射与参数接收
确认SpringBoot中对应接口的@PostMapping路径是否为/monitoring/update,且参数接收是否正确使用@RequestBody注解。如果接口误用了@PutMapping或者没加@RequestBody,会导致请求无法正常处理,浏览器将其判定为CORS错误。
正确的接口示例:@PostMapping("/update") public ResponseEntity<String> updateMonitoringData(@RequestBody MonitoringDto dto) { // 业务逻辑处理 return ResponseEntity.ok("Success"); }替换为全局跨域配置
控制器级的@CrossOrigin可能因配置冲突不生效,改用全局CORS配置更可靠:@Configuration public class GlobalCorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .maxAge(3600); } }若前端需要携带Cookie,需将
allowedOrigins指定为具体域名(如http://localhost:3000),并设置allowCredentials(true)。确保OPTIONS预检请求被放行
如果项目使用Spring Security或自定义拦截器,需明确放行OPTIONS请求:
Spring Security配置示例:@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and() .authorizeRequests() .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 其他权限配置 .anyRequest().authenticated(); } }检查请求体数据格式
浏览器控制台的CORS错误可能是“假象”,实际是请求体数据格式不符合接口要求(比如modifiedDate格式不被SpringBoot解析)。查看SpringBoot后台日志,确认是否存在JSON解析异常,调整前端数据格式即可解决。
内容的提问来源于stack exchange,提问作者Gagak
相关产品推荐
相关产品推荐

