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

React POST请求遭CORS拦截求助(附前后端配置代码)

CORS跨域请求拦截问题排查

发起POST请求时出现以下错误:

从源 'http://localhost:3000' 访问 'http://localhost:8080/profile/v2/add/post' 的XMLHttpRequest被CORS策略阻止:预检请求的响应未通过访问控制检查:请求的资源上不存在 'Access-Control-Allow-Origin' 标头。

React POST请求代码

// React POST 请求代码
export const BASE_URL = "http://localhost:8080";

export const myAxios = axios.create({
  baseURL: BASE_URL,
});

export const privateAxios = axios.create({
  baseURL: BASE_URL,
  headers: {
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*",
    
  },
 
});

privateAxios.interceptors.request.use(
  (config) => {
    const token = getToken();

    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }

    return config;
  },
  (error) => Promise.reject(error)
);

export const createPost = (user) => {
  return  privateAxios
    .post("/profile/v2/add/post", user)
    .then((val) => {
      console.log(val);
    })
    .catch((err) => console.log(err));
};

Spring Boot CORS配置代码

// Spring Boot CORS 配置
@Bean
public FilterRegistrationBean crossFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));

    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.addAllowedOriginPattern("*");
    corsConfiguration.addAllowedHeader("Authorization");
    corsConfiguration.addAllowedHeader("Content-Type");
    corsConfiguration.addAllowedHeader("Accept");
    corsConfiguration.addAllowedMethod("POST");
    corsConfiguration.addAllowedMethod("PUT");
    corsConfiguration.addAllowedMethod("GET");
    corsConfiguration.addAllowedMethod("DELETE");
    corsConfiguration.addAllowedMethod("OPTIONS");
    corsConfiguration.setMaxAge(3600L);
    source.registerCorsConfiguration("/**", corsConfiguration);

    return bean;
}

问题排查与修复方案

  1. 移除请求中的Access-Control-Allow-Origin头
    这个头是服务端返回给客户端的响应头,不需要在客户端请求时发送。在privateAxios配置里删除该头:

    export const privateAxios = axios.create({
      baseURL: BASE_URL,
      headers: {
        "Content-Type": "application/json"
        // 移除 "Access-Control-Allow-Origin": "*"
      },
    });
    
  2. 调整Spring Boot过滤器优先级
    CORS过滤器可能被其他过滤器拦截,导致预检请求未被正确处理。给过滤器设置最高优先级:

    @Bean
    public FilterRegistrationBean crossFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsFilter corsFilter = new CorsFilter(source);
        FilterRegistrationBean bean = new FilterRegistrationBean(corsFilter);
        
        // 设置最高优先级,确保先处理CORS请求
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.addAllowedHeader("*"); // 允许所有请求头,避免遗漏
        corsConfiguration.addAllowedMethod("*"); // 允许所有HTTP方法
        corsConfiguration.setMaxAge(3600L);
        source.registerCorsConfiguration("/**", corsConfiguration);
    
        return bean;
    }
    

    改用*允许所有请求头和方法,简化配置同时避免遗漏。

  3. 验证预检请求响应
    打开浏览器开发者工具(F12)→ Network标签,找到OPTIONS类型的预检请求,查看响应头是否包含Access-Control-Allow-Origin、Access-Control-Allow-Methods等关键头。如果没有,说明CORS配置未生效,需检查过滤器注册逻辑。

  4. 快速验证:使用@CrossOrigin注解
    若全局过滤器配置有问题,可在对应Controller类或方法上添加注解快速验证:

    @RestController
    @CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS})
    public class PostController {
        @PostMapping("/profile/v2/add/post")
        public ResponseEntity<?> createPost(@RequestBody User user) {
            // 业务逻辑实现
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 20:45:23