You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot与React Axios调用DELETE接口出现CORS错误如何解决

解决方案
  • 第一步:清理前端Axios错误请求头

    CORS相关的Access-Control-*头是服务端返回的响应头,不需要前端主动在请求里添加,你加了这些头之后会让浏览器的预检OPTIONS请求额外校验这些头部权限,反而触发跨域错误。修改后的Axios代码如下:
    return axios({
        method:'DELETE',
        url:`http://localhost:8080/testdelete`,
        data: data,
        headers: {
            'Content-Type': 'application/json'
        }
    }) 
    
  • 第二步:修正Spring Boot @CrossOrigin配置错误

    你当前配置的origins地址末尾多了斜杠,和实际请求的origin值http://localhost:3000匹配失败,同时可以补充允许的头部配置,修改后的Controller注解如下:
    @CrossOrigin(origins = {"http://localhost:3000"},
    methods = {RequestMethod.GET,RequestMethod.POST,RequestMethod.DELETE,RequestMethod.OPTIONS},
    allowedHeaders = "*")
    @RestController
    public class TestDelete {
        @DeleteMapping("/testdelete")   
        public ResponseEntity<void> deleteData(@RequestBody Data data) throws Exception {
            // 业务逻辑
        }
    }
    
  • 第三步:特殊场景补充配置

    如果做完上面两步还是报错,按以下场景排查:
    1. 如果你项目里集成了Spring Security,需要额外配置放行OPTIONS类型的预检请求,避免预检请求被权限拦截,导致没有返回CORS响应头
    2. 如果你有多个Controller需要配置跨域,可以改用全局跨域配置,避免每个类都加@CrossOrigin注解,新增配置类即可:
    @Configuration
    public class CorsConfig implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("http://localhost:3000")
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                    .allowedHeaders("*")
                    .allowCredentials(true);
        }
    }
    

内容的提问来源于stack exchange,提问作者Hussain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 21:06:04