1. 跨域介绍
首先解释什么是跨域,跨域就是前端和后端的端口号不同;会产生跨域问题,这里浏览器的保护机制(同源策略)。
同源策略:前端和后端的协议、域名、端口号三者都相同叫做同源。
我们看一下不同源:
VUE:http://localhost:8080
Spring: http://localhost:8081/list
当我们出现跨域问题,前端就会报一个错(篮框扩这那个):
2. 解决方法
上方就是不同源,两者的协议、域名相同,但是端口号不同;如何解决呢,使用Spring Boot解决,它提供三种方案:
- 直接在方法上方添加@CrossOrigin注解即可解决问题
@CrossOrigin@RequestMapping("/getuserbyid")publicUserInfogetUserById(Integer id){if(id ==null)returnnull;return userService.getUserById(id);}
- 添加 CORS 过滤器
importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.cors.CorsConfiguration;importorg.springframework.web.cors.UrlBasedCorsConfigurationSource;importorg.springframework.web.filter.CorsFilter;@ConfigurationpublicclassCorsConfig{@BeanpublicCorsFiltercorsFilter(){CorsConfiguration corsConfiguration =newCorsConfiguration();
corsConfiguration.setAllowCredentials(true);// 允许cookies跨域
corsConfiguration.addAllowedHeader("*");// 请求头字段
corsConfiguration.addAllowedMethod("*");// 方法
corsConfiguration.addAllowedOrigin("*");// 允许向该服务器提交请求的URI,*表示全部允许,自定义可以添加多个,在SpringMVC中,如果设成*,会自动转成当前请求头中的OriginUrlBasedCorsConfigurationSource source =newUrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**",corsConfiguration);// 添加映射路径,以及参数returnnewCorsFilter(source);}}
- 重写 WebMvcConfigurer 接口中的 addCorsMappings 方法
importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.CorsRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;@ConfigurationpublicclassWebConfigimplementsWebMvcConfigurer{@OverridepublicvoidaddCorsMappings(CorsRegistry registry){// 先设置映射
registry.addMapping("/**").allowedOriginPatterns("*")// 允许向该服务器提交请求的URI,*表示全部允许,自定义可以添加多个,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin.allowCredentials(true)// 允许cookies跨域.allowedHeaders("*")// 请求头字段.allowedMethods("GET","POST")// 允许跨域的方法.maxAge(3600);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了}}
版权归原作者 爱吃大白菜 所有, 如有侵权,请联系我们删除。