彻底理解什么是跨域以及如何解决跨域
同源策略
同源与跨域
跨域调用,会出现如下错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access. The response had HTTP status code 400.
CORS简介
解决跨域
1.基于注解驱动
使用@CrossOrigin注解,该注解有以下属性:
属性 | 含义 |
---|---|
value | 指定所支持域的集合,表示所有域都支持,默认值为。这些值对应HTTP请求头中的Access-Control-Allow-Origin |
origins | 同value |
allowedHeaders | 允许请求头中的header,默认都支持 |
exposedHeaders | 响应头中允许访问的header,默认为空 |
methods | 支持请求的方法,比如GET,POST,PUT等,默认和Controller中的方法上标注的一致。 |
allowCredentials | 是否允许cookie随请求发送,使用时必须指定具体的域 |
maxAge | 预请求的结果的有效期,默认30分钟 |
使用CORS实现跨域,只需添加一个 @CrossOrigin注解,该注解可以标注于方法或者类上。
@CrossOrigin
public class testController{
}
2.基于接口编程
使用接口编程的方式进行统一配置。创建配置类实现WebMvcConfigurer,重写addCorsMappings默认实现即可
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
// 为url添加映射路径
registry.addMapping("/**")
// 设置允许的域
.allowedOrigins("*")
// 设置允许请求的方式
.allowedMethods("*")
// 设置允许的header
.allowedHeaders("*")
// 设置是否发送cookie信息
.allowCredentials(true);
}
}
3.基于过滤器
创建一个CorsConfig配置类,基于过滤器实现全局跨域配置。
@Configuration
public class CorsConfig {
public CorsConfig() {
}
@Bean
public CorsFilter corsFilter() {
// 1. 添加cors配置信息
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("http://localhost:8080");
config.addAllowedOrigin("http://localhost:8081");
config.addAllowedOrigin("http://localhost:8082");
config.addAllowedOrigin("*");
// 设置是否发送cookie信息
config.setAllowCredentials(true);
// 设置允许请求的方式
config.addAllowedMethod("*");
// 设置允许的header
config.addAllowedHeader("*");
// 2. 为url添加映射路径
UrlBasedCorsConfigurationSource corsSource = new UrlBasedCorsConfigurationSource();
corsSource.registerCorsConfiguration("/**", config);
// 3. 返回重新定义好的corsSource
return new CorsFilter(corsSource);
}
}
4.基于微服务网关配置
spring.cloud.gateway.routes[1].id=system
#spring.cloud.gateway.routes[1].uri=http://127.0.0.1:8888
spring.cloud.gateway.routes[1].uri=lb://system
spring.cloud.gateway.routes[1].predicates[0].name=Path
spring.cloud.gateway.routes[1].predicates[0].args[0]=/system/**
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;
/**
* 配置跨域
* @return
*/
@Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(Boolean.TRUE);
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}