什么是跨域问题:
跨域:
指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制。
同源策略:
是指协议,域名,端口都要相同,其中有一个不同都会产生跨域;
跨域流程:非简单请求(PUT、DELETE)等,需要先发送预检请求。
解决跨域 方法一
使用nginx 部署为同一域
解决跨域方法二 配置当次请求允许跨域
通过添加响应头解决
Access-Control-Allow-Origin:支持哪些来源的请求跨域。
Access-Control-Allow-Methods:支持哪些方法跨域。
Access-Control-Allow-Credentials:跨域请求默认不包含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:表明该响应的有效时间为多少秒。在有效时间内,浏览器无须为同一请求再次发起预检请求。请注意,浏览器自身维护了一个最大有效时间,如果该首部字段的值超过了最大有效时间,将不会生效。
四 跨域问题现象
1 抓包时呈现的现象
五 网关统一配置允许跨域
@Configuration
public class GulimallCorsConfiguration {
/**
* 功能描述:网关统一配置允许跨域
* @return CorsWebFilter 跨域配置过滤器
*/
@Bean
public CorsWebFilter corsWebFilter(){
// 跨域配置源
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 跨域配置
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 1 配置跨域
// 允许所有头进行跨域
corsConfiguration.addAllowedHeader("*");
// 允许所有请求方式进行跨域
corsConfiguration.addAllowedMethod("*");
// 允许所有请求来源进行跨域
corsConfiguration.addAllowedOrigin("*");
// 允许携带cookie进行跨域
corsConfiguration.setAllowCredentials(true);
// 2 任意路径都允许第1步配置的跨域
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}
1 抓包时呈现的现象
gulimall-gateway的 application.yml 配置如下
spring:
cloud:
gateway:
routes:
- id: product_route
uri: lb://gulimall-product
predicates:
- Path=/api/product/**,/hello
filters:
- RewritePath=/api/(?<segment>.*),/$\{segment}
- id: admin_route
uri: lb://renren-fast
predicates:
- Path=/api/**
filters:
- RewritePath=/api/(?<segment>.*),/renren-fast/$\{segment}