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;
/**
* 跨域配置
*/
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setMaxAge(1728000L);
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("PUT");
corsConfiguration.addAllowedMethod("GET");
corsConfiguration.addAllowedMethod("POST");
corsConfiguration.addAllowedMethod("PATCH");
corsConfiguration.addAllowedMethod("OPTIONS");
corsConfiguration.addAllowedMethod("DELETE");
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
使用配置文件解决SpringBoot接口跨域问题
于 2020-04-26 11:10:33 首次发布
本文详细介绍了一种在SpringBoot中实现跨域请求的方法。通过创建一个配置类,使用@Bean注解定义CorsFilter实例,设置允许所有源、凭证、请求头和多种HTTP方法,如GET、POST、PUT等,同时设定最大年龄为1728000毫秒。此配置全面覆盖了RESTful API的所有需求。
919

被折叠的 条评论
为什么被折叠?



