本地服务器部署前后端同IP跨域报错,配置CORS仍未解决求助
解决方案:同IP不同端口下的CORS错误排查
先梳理你的问题:前后端都绑定192.168.50.41不同端口时触发CORS错误,但跨IP或混用localhost的组合却正常运行,已经配置了allowed-origins和Security的cors()但未生效。以下是几个核心修复方向:
1. 补全CORS配置参数并修正格式
你的application.yml配置缺少几个关键项,且格式存在问题。修改为数组结构,同时添加预检请求必需的方法、头信息配置:
cors: allowed-origins: - http://192.168.50.41:3000 allowed-endpoints: - /api/v1/auth/login - /api/v1/auth/register allowed-methods: "*" allowed-headers: "*" allow-credentials: true
其他组合正常的原因是:localhost与IP混合时,浏览器Origin会被Spring默认CORS规则宽松处理,但同IP时严格匹配,缺少参数就直接触发拦截。
2. 让Spring Security正确读取CORS配置
仅在yml中配置无法让Security的cors()模块加载规则,需要自定义CorsConfigurationSource Bean:
@Configuration @ConfigurationProperties(prefix = "cors") public class CorsConfig { private List<String> allowedOrigins; private List<String> allowedEndpoints; private List<String> allowedMethods; private List<String> allowedHeaders; private boolean allowCredentials; // 自动生成getter、setter方法 @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(allowedOrigins); config.setAllowedMethods(allowedMethods); config.setAllowedHeaders(allowedHeaders); config.setAllowCredentials(allowCredentials); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); allowedEndpoints.forEach(endpoint -> source.registerCorsConfiguration(endpoint, config)); return source; } }
然后在Security配置中指定使用这个自定义配置源:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http, CorsConfigurationSource corsConfigurationSource) throws Exception { http .cors(cors -> cors.configurationSource(corsConfigurationSource)) .and() .csrf().disable() .exceptionHandling().authenticationEntryPoint(authEntryPoint) .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeHttpRequests(auth -> auth .requestMatchers("/api/v1/auth/login").permitAll() .anyRequest().authenticated() ) .authenticationProvider(authenticationProvider) .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); }
3. 排查预检请求状态
如果以上配置仍未解决问题,打开浏览器控制台网络面板,检查OPTIONS预检请求:
- 确认
Access-Control-Allow-Origin响应头与前端请求的Origin完全一致 - 检查
Access-Control-Allow-Methods包含你实际使用的请求方法(POST/GET等) - 确保OPTIONS请求状态码为200,而非403或其他错误
注意:不要手动处理OPTIONS请求,交给Spring的CORS过滤器自动处理即可。
内容的提问来源于stack exchange,提问作者user
相关产品推荐
相关产品推荐

