跨域问题

it2025-05-14  10

跨域

跨域 指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的, 是浏览器对javascript时间的安全显示。 同源策略: 是指协议,域名,端口都要相同,其中有一个不同都会产生跨域;

解决跨域方式

1.使用Nginx部署为同一域

前端,后端都放到nginx上,访问请求都发送到Nginx上,由Nginx转发相应的服务;

2.配置当次请求允许跨域

分析: 每次发请求结束后都添加请求头太麻烦了,所有用Filter来解决.所有请求进来后放行,执行完返回给浏览器之前给响应里添加请求头字段。而在微服务的项目中,这个Filter并不用写在每一个服务当中,因为大多数情况下,我们都会用到网关。所以我们只需在网关里统一配置跨域

@Configuration public class MyConfigCorsConfiguration { @Bean public CorsWebFilter corsWebFilter(){ // CorsConfigurationSource corsConfigurationSource = new CorsConfigurationSource() { // @Override // public org.springframework.web.cors.CorsConfiguration getCorsConfiguration(ServerWebExchange serverWebExchange) { // return null; // } // }; UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(); CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); corsConfiguration.addAllowedMethod("GET\", \"POST\", \"PUT\", \"DELETE\", \"OPTIONS"); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.setAllowCredentials(true); urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration); return new CorsWebFilter(urlBasedCorsConfigurationSource); } }
最新回复(0)