方法一:@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 跨域系统配置
*/
@Configuration
public class CorsConfig {
/**
允许任何域名使用
允许任何头
允许任何方法(post、get等)
*/
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
// // addAllowedOrigin 不能设置为* 因为与 allowCredential 冲突,需要设置为具体前端开发地址
corsConfiguration.addAllowedOrigin("*");//前端的开发地址
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
// allowCredential 需设置为true
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
网友评论