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

CORS拦截PUT/DELETE/POST但GET正常,Postman可用React axios不可用如何解决

问题根因及修复方案

1. CORS配置重复导致自定义规则未生效

你在configure(HttpSecurity http)方法中手动指定了默认CORS配置:

http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues())

这行配置会直接覆盖你后续声明的corsConfigurationSource() Bean的自定义规则,而applyPermitDefaultValues()默认仅允许GET、HEAD、POST三类请求,DELETE请求默认被拦截。
修复方式:删除configurationSource的配置,仅保留http.cors().and()即可,Spring Security会自动加载你声明的CORS配置Bean。

2. 凭证允许规则与通配符来源冲突

你同时配置了setAllowCredentials(true)和setAllowedOrigins(Arrays.asList("*")),Spring CORS校验规则不允许在开启凭证传递时使用通配符作为允许来源,会直接导致配置失效。
修复方式:将setAllowedOrigins替换为setAllowedOriginPatterns:

// 替换原setAllowedOrigins配置
configuration.setAllowedOriginPatterns(Arrays.asList("*"));

生产环境建议明确填写前端地址,比如Arrays.asList("http://localhost:3000"),安全性更高。

3. OPTIONS预检请求未被放行

浏览器发起跨域非简单请求前会先发送OPTIONS方法的预检请求,该请求不会携带Authorization头,会被你当前的认证规则拦截,返回401状态码,响应中不会包含CORS头,最终导致预检失败。
修复方式:在权限配置中添加OPTIONS请求的放行规则:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf()
            .disable().authorizeRequests()
            .antMatchers("/api/authenticate").permitAll()
            // 新增放行所有OPTIONS预检请求
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .anyRequest().authenticated()
            .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}

修改完成后重启后端服务即可正常调用DELETE接口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:39:03