跨域请求一般用于前后台分离,前台和后台不是统一个项目,所以在前端请求的时候就会报错,请求不被允许。这就需要配置跨域请求了,由于项目是使用SpringBoot开发,这里贴出基于Springboot的配置。
第一步:写一个配置类来封装跨域请求参数,省略get,Set
|
@Configuration
@ConditionalOnWebApplication @EnableConfigurationProperties(CorsProperties.class) @ConditionalOnProperty(prefix = "cors", name = "enabled", havingValue = "true") public class CorsAutoConfiguration extends WebMvcConfigurerAdapter { @Autowired private CorsProperties properties; @Override public void addCorsMappings(CorsRegistry registry) { CorsRegistration corsRegistration = registry.addMapping(properties.getMappingPathPattern()); corsRegistration.allowedOrigins(properties.getAllowedOrigins()) .allowedHeaders(properties.getAllowedHeaders()) .maxAge(properties.getMaxAge()) .allowCredentials(properties.getAllowCredentials());
if (properties.getAllowedMethods() != null) { corsRegistration.allowedMethods(properties.getAllowedMethods()); } if (properties.getExposedHeaders() != null) { corsRegistration.exposedHeaders(properties.getExposedHeaders()); } } } |
#跨域请求配置 # 必选。启用cors,值是一个布尔值 cors.enabled=true # 必选。它的值要么是请求时Origin字段的值,要么是一个*,表示接受任意域名的请求 cors.allow-origin=* cors.allow-headers=Content-Type, Cache-Control, Pragma, Origin, Cookie, Link, Authorization, * |
实际开发中,下面一种也是可行的,参考配置如下:
import org.springframework.boot.web.servlet.FilterRegistrationBean; 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 wll */ @Configuration public class CrosConfig { @Bean public FilterRegistrationBean corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // 设置要允许的网站域名http://localhost:4200 ,如果全允许则设为 * config.addAllowedOrigin("*"); // 如果要限制 HEADER 或 METHOD 请自行更改 config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); // 这个顺序很重要哦,为避免麻烦请设置在最前 bean.setOrder(0); return bean; } }