1、普通spring mvc项目
//java项目www.fhadmin.org
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); // 允许cookies跨域
//config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin
config.addAllowedOriginPattern("*");//springboot2.4.2中addAllowedOrigin不允许设置为*,要改成使用AllowedOriginPattern
config.addAllowedHeader("*");// #允许访问的头信息,*表示全部
config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
config.addAllowedMethod("*");// 允许提交请求的方法,*表示全部允许
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
2、webflux项目
package com.dream.web.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;
//java项目www.fhadmin.org
@Configuration
public class CorsConfig {
/**
* webflux中的reactive的拦截器
* @return
*/
@Bean
public CorsWebFilter corsWebFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); // 允许cookies跨域
config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin
config.addAllowedHeader("*");// #允许访问的头信息,*表示全部
config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
config.addAllowedMethod("*");// 允许提交请求的方法,*表示全部允许
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
3、spring cloud gateway网关全局配置
spring:
cloud:
# spring cloud gateway配置
gateway:
# 全局跨域
globalcors:
# 跨域配置(可以在代码里面处理允许跨域,也可在这里全局处理)
corsConfigurations:
'[/**]':
allowedOrigins: "*"
allowedHeaders: "*"
allowCredentials: true
allowedMethods:
- GET
- POST
- OPTIONS
- DELETE
- PUT
- HEAD
- PATCH