1、直接上注解:@CrossOrigin //在controller类上添加此注解
直接在需要跨域的Controller的类上添加 @CrossOrigin 跨域注解即可。
2、服务中的 CorsFilter ,这个 spring webmvc 中给出过滤器层面的跨域
当一个模块中controlller过多时,添加注解过于繁琐,可以创建一个配置类对象,进行跨域设置,'' FilterRegistrationBean<Corsfilter> ''。
package com.example.gupan.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//标注这个类是一个配置类
@Configuration
//实现 WebMvcConfigurer 接口
public class CorsWebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") //设置允许跨域访问的路径
.allowedOriginPatterns("*") //设置允许跨域访问的源
.allowedMethods("POST", "GET") //允许跨域请求的方法
.maxAge(168000) //预检间隔时间
.allowedHeaders("*") //允许头部设置
.allowCredentials(true); //是否发送 cookie
}
}
3、网关中的CorsWebFilter ,这个是spring webflux中的过滤器
一个网关管理多个服务时,设置此配置类对象,可以从网关层面解决多个服务的跨域问题,这就不需要每个服务都写一遍跨域了。
package com.example.gupan.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
@Configuration
public class CorsFilterConfig {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsWebFilter(source);
}
}
注:关于此处配置后报错:
主要就是缺少了下面的依赖,添加之后就OK了
<!-- 引入 Webflux 依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
4、通过 配置文件 进行跨域设置(微服务项目下推荐使用此方法)
此方法在微服务项目下可以配置到nacos等配置中心, 未来项目发布后能更灵活的处理各种请求。
spring:
cloud:
gateway:
globalcors: #跨域配置
corsConfigurations:
'[/**]':
allowedOrigins: "*"
allowedHeaders: "*"
allowedMethods: "*"
allowCredentials: true