配置类(若在网关层配置了CORS,在项目中可以去掉此配置)
配置一
/**
*
-
解决前端:Access-Control-Allow-Origin
-
extends WebMvcConfigurerAdapter OR extends WebMvcConfigurationSupport OR implements WebMvcConfigurer
-
but WebMvcConfigurerAdapter is Deprecated
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(true);
}
}
配置二
@Configuration
public class WebMvcConfig {
@Bean
@ConditionalOnMissingBean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedHeaders(Collections.singletonList("*"));
corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE"));
corsConfiguration.setAllowedOrigins(Collections.singletonList("*"));
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setExposedHeaders(Arrays.asList("File-Name","refresh_token"));
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
说明
无论是通过哪种方式配置 CORS,其实都是在构造 CorsConfiguration。 一个 CORS 配置用一个 CorsConfiguration类来表示。
}