一、前后端分离导致的请求路径问题
后端有各种微服务,不同的例如Product(10002),Order(9001),Ware(11001)。
因此通过WebSocket访问存在两个问题:
- 不同服务有不同的端口,难以管理,很容易出错
- 分布式情况下,同一个服务会有多个实例,每个实例的端口也不一样,例如Product就可以有10001,10002,10003等等
因此将前端请求的基准地址改为88端口,发送给网关同一处理。
// api接口请求地址
window.SITE_CONFIG['baseUrl'] = 'http://localhost:88/api';
再通过网关重写路径http://localhost:88/api/captcha.jpg ====> http://localhost:8080/renren-fast/captcha.jpg
#将路径为Path=/api/**转发至后台管理
- id: admin_route
uri: lb://renren-fast #lb表示负载均衡
predicates:
- Path=/api/**
filters:
- RewritePath=/api/(?<segment>.*), /renren-fast/$\{segment}
#RewritePath路径重写
#http://localhost:88/api/captcha.jpg ====> http://localhost:8080/renren-fast/captcha.jpg
不过就此出现了跨域的问题:
二、跨域问题
跨域:指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript施加的安全限制。
同源策略:是指协议、域名、端口都要相同,其中有一个不同都会产生跨域。
跨域的流程如下:
三、跨域解决方法
方法1、使用Nginx部署为同一域
方法2、配置当前请求允许跨域
在网关设置一个corsWebFilter,为所有的请求添加响应头,允许跨域。
@Configuration
public class GulimallCorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
//跨域请求暴露的字段
corsConfiguration.addAllowedHeader("*");
//支持哪些方法跨域
corsConfiguration.addAllowedMethod("*");
//支持哪些来源的请求跨域
corsConfiguration.addAllowedOrigin("*");
//跨域请求默认不包含cookie,设置为true可以包含 cookie
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}
之后每次请求的请求头结果如下: