配置网关springcloud-gateway
当前端访问后端服务的时候,有前端发送给网关,然后由网关发送给各个服务,并使用负载均衡策略。
- 网关使用负载均衡,所以将服务renren-fast服务添加到注册中心
- 配置网关服务的配置文件,将地址转发到相应的服务(路径转发的配置,断言的规则)
spring:
application:
name: gulimall-gateway
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
gateway:
routes:
- id: test_route
uri: https://www.baidu.com
predicates:
- Query=url,baidu
- id: qq_route
uri: https://www.qq.com
predicates:
- Query=url,qq
- id: product_route
uri: lb://renren-fast # lb://服务名称 实现负载均衡
predicates:
- Path=/api/** # 表示所有递归子目录
filters:
- RewritePath=/api/(?<segment>.*),/renren-fast/$\{segment}
# - RewritePath=/api/(?<segment>/?.*), /renren-fast/$\{segment}
# /api/(?<segment>/?.*), $\{segment} === 将/api/bar 这个请求 重写成/bar
# 规定:前端路径都带有/api
#前端地址:http://localhost:88/api/captcha.jpa---转发---> http://renren-fast:8080/api/captcha.jpa
# 但是由于renren-fast 项目中配置了server.servlet.context-path = renren-fast
# 所以地址应该是 http://renren-fast:8080/renren-fast/captcha.jpa 才可以
解决跨域问题
什么是跨域?
跨域流程
当不是简单请求的时候,会出现两次请求,第一次为OPTIONS请求,第二次才是真正的请求。
什么不是简单的请求? delete , put 等请求。
什么是简单的请求? get post 请求,并且Content-Type 是
text/plain
multipart/form-data
application/x-www-form-urlencoded
这三种形式,假如post请求的Content-type不是这三种形式,也属于复杂请求
跨域请求文档
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
跨域的解决办法
- 使用Nginx统一代理,转发到同一域。
- 在网关上使用过滤器,设置头head或者请求方式或者请求来源可以实现跨域的问题。
使用过滤器添加头信息,表明可以跨域,参数有以下形式。
过滤代码展示:使用过滤器进行对url地址实现跨域 的操作。过滤器springboot封装好了,我们只需要实现CorsWebFilter接口就可以,并注入到容器中。
@Configuration
public class GulimallCorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
//1、配置跨域
corsConfiguration.addAllowedHeader("*"); //任何头部都可以跨域
corsConfiguration.addAllowedMethod("*"); //任何请求方式都可跨域
corsConfiguration.addAllowedOrigin("*"); //任何请求来源都可以跨域
corsConfiguration.setAllowCredentials(true); //允许cooke携带进行跨域
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}