在SpringBoot2.0 上的跨域 用以下代碼配置 即可完美解決你的前后端跨域請求問題
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 linhongcun
*
*/
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
/*是否允許請求帶有驗證信息*/
corsConfiguration.setAllowCredentials(true);
/*允許訪問的客戶端域名*/
corsConfiguration.addAllowedOrigin("*");
/*允許服務端訪問的客戶端請求頭*/
corsConfiguration.addAllowedHeader("*");
/*允許訪問的方法名,GET POST等*/
corsConfiguration.addAllowedMethod("*");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}