方法一:@CrossOrigin
使用@CrossOrigin注解滨砍,在@RestController上添加@CrossOrigin
spring4.2以上支持
方法二: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 cc
* @Date 2018-09-20
* @DESCRIPTION 跨域系統(tǒng)配置
*/
@Configuration
public class CorsConfig {
/**
允許任何域名使用
允許任何頭
允許任何方法(post、get等)
*/
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
// // addAllowedOrigin 不能設(shè)置為* 因為與 allowCredential 沖突,需要設(shè)置為具體前端開發(fā)地址
corsConfiguration.addAllowedOrigin("*");//前端的開發(fā)地址
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
// allowCredential 需設(shè)置為true
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}