1.解决跨域请求的2种方法
- 使用 nginx 配置,所有请求都被 nginx 配置到同一域中,然后反向代理到其它服务
- 让服务器告诉预检请求能跨域
我采用第二种方法
2.解决跨域
2.1.配置当次请求允许跨域
- Access-Control-Allow-Origin:支持哪些来源的请求
- Access-Control-Allow-Methods:支持哪些方法跨域(GET、POST…)
- Access-Control-Allow-Gredentials:跨域请求默认不包含 Cookie,设置 true 可以包含 Cookie
- Access-Control-Expose-Headers::跨域请求暴露手段
CORS请求时,XMLHttpRequest 对象的 getResponseHeader()方法只能拿到6个基本字段: Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma. 如果想拿到其他字段,就必须在Access-Control-Expose-Headers 里面指定。
- Access-Control-Max-Age:表明该响应的有效时间为多少秒。在有效时间内,浏览器无须为同一请求再次发起预检请求。请注意,浏览器自身维护了一个最大有效时间,如果该首部字段的值超过了最大有效时间,将不会生效。
2.2.编码
第一种
@Configuration
public class GulimallCorsConfiguration {
/**
* 添加跨域过滤器
* @return CorsWebFilter
*/
@Bean
public CorsWebFilter corsWebFilter() {
// 基于url跨域,选择reactive包下的
UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
// 跨域配置信息
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 允许跨域的头
corsConfiguration.addAllowedHeader("*");
// 允许跨域的请求方式
corsConfiguration.addAllowedMethod("*");
// 允许跨域的请求来源
corsConfiguration.addAllowedOrigin("*");
// 是否允许携带cookie跨域
corsConfiguration.setAllowCredentials(true);
// 任意url都要进行跨域配置
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}
第二种: 实现 SpringMVC
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.maxAge(3600);
}
}