直接新建一个CorsConfig类,把一下代码粘贴就可以了
需要注意的是,设置允许跨域请求的源地址和请求头时,应该只允许必要的来源和请求头,以避免潜在的安全风险。
另外,需要根据具体的业务需求,对跨域请求的有效时长进行合理的设置。
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;
/**
* @author ice
*/
@Configuration
public class CorsConfig {
/**
* 当前跨域请求最大有效时长。这里默认1天
*/
private static final long MAX_AGE = 24 * 60 * 60;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 1 设置访问源地址
corsConfiguration.addAllowedOrigin("*");
// 2 设置访问源请求头
corsConfiguration.addAllowedHeader("*");
// 3 设置访问源请求方法
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setMaxAge(MAX_AGE);
// 4 对接口配置跨域设置
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}