跨域是指请求违反了浏览器的同源策略(要求请求url中的协议、域名、端口,三者都相同)。真实的情况是后端接收到请求了,也给前端返回了数据,但是浏览器利用自身的保护机制拦截数据,拒绝展示,导致控制台报错。
在 SpringBoot项目中可以用多种方法解决跨域问题。
方案一:在目标方法上添加@CrossOrigin
注解
@GetMapping("/list") @CrossOrigin public List<String> list(){ List<String> list = Arrays.asList("Java","C++","Go"); return list; }
|
适用于针对性很强的情况,如果需要处理的方法非常多,每个都加注解就很麻烦。
方案二:添加CORS过滤器作为配置类
新建一个package,取名为configuration
,添加配置类:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter;
@Configuration public class CorsConfig {
@Bean public CorsFilter corsFilter(){ CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedMethod("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsFilter(source); } }
|
新建一个package,取名为configuration
,添加配置类:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET","POST","PUT","DELETE","HEAD","OPTIONS") .allowedHeaders("*") .allowCredentials(true) .maxAge(3600); } }
|
https://www.bilibili.com/video/BV12U4y1f7Qi