1. 在控制层上加注解 @CrossOrigin
@CrossOrigin
@Api(tags = "用户基本信息")
@RestController
@RequestMapping("/api/core/userInfo")
public class ApiUserInfoController {
}
2. 开启跨域资源共享
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
// 设置你要允许的网站域名
config.addAllowedOrigin("http://localhost:8080");
//允许跨域发送cookie
config.setAllowCredentials(true);
//放行全部原始头信息
config.addAllowedHeader("*");
//允许所有请求方法跨域调用
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
3. 配置网关统一跨域
@Configuration
public class GatewayConfig {
/*
springmvc:
在Controller或者它的接口上使用//@CrossOrigin注解
gateway:
配置CorsWebFilter设置允许跨域
*/
@Bean
public CorsWebFilter corsWebFilter() {
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");//哪些请求方式允许跨域访问
config.addAllowedHeader("*");//允许携带哪些请求头跨域访问
config.addAllowedOrigin("*");//允许哪些origin跨域访问
config.setAllowCredentials(true);//是否允许携带cookie跨域访问
configSource.registerCorsConfiguration("/**", config);
// configSource.registerCorsConfiguration("/**/sms/**",config2);
return new CorsWebFilter(configSource);
}
}