欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > SpringBoot3中跨域问题解决

SpringBoot3中跨域问题解决

2025/2/22 22:23:47 来源:https://blog.csdn.net/jioujiou520/article/details/145768532  浏览:    关键词:SpringBoot3中跨域问题解决

问题

SpringBoot3 中处理跨域请求

异常

浏览器在 localhost:3000 地址请求后端 http://127.0.0.1:8080 时, 报错提示 CORS 问题.
默认使用 Get 请求正常, 其他会提示.
使用 SpringBoot 3.4.2 版本配合 SpringSecurity 配置

Access to fetch at 'http://127.0.0.1:8080/todo-task/list' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

解决

需要在 Spring Security 配置以下内容…


/*** Spring Security 配置** @author Jion*/
@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig {private final JwtAuthenticationFilter jwtAuthenticationFilter;private final CustomAuthenticationEntryPoint unauthorizedHandler;/*** 配置过滤器链** @param http 请求* @return 过滤器链* @throws Exception 抛出异常*/@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {// 一些其他配置等...// 跨域请求http.cors(corsConfigurer -> corsConfigurer.configurationSource(corsConfigurationSource()));return http.build();}/*** 跨域配置, 仅在开发环境有必要.* 如果是发布之后, 桌面应用不会产生跨域问题.*/@Beanpublic UrlBasedCorsConfigurationSource corsConfigurationSource() {CorsConfiguration configuration = new CorsConfiguration();// 允许本地域名访问configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000", "http://127.0.0.1:3000"));// 允许被本地域名访问configuration.setAllowedOriginPatterns(Arrays.asList("http://localhost:3000/**", "http://127.0.0.1:3000/**"));// 允许所有请求方法configuration.setAllowedMethods(List.of("*"));// 允许所有请求头configuration.setAllowedHeaders(List.of("*"));// 允许所有响应头configuration.setExposedHeaders(List.of("*"));// 允许携带凭证configuration.setAllowCredentials(true);// 跨域请求配置UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();// 匹配所有请求路径source.registerCorsConfiguration("/**", configuration);return source;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词