springcloud-gateway搭建、跨域、路由重写相关

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

提示::

官方开发文档地址

https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/


提示:

一、gateway搭建

1. pom

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

2. yaml

1 注册

要使用gateway,先注入到服务注册中心中,以alibaba下的开源nacos为例

spring:
  application:
    name: gulimall-gateway
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848

2 配置路由与路径重写

再去配置gateway相关yaml,这里以配置路由(routes)和路径重写(RewritePath)

spring:
  application:
    name: gulimall-gateway
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    gateway:
      routes:
        #==========================以api开头的都是前端发请求==============
        - id: product_route #处理商品服务,精确路由
          uri: lb://gulimall-product
          predicates:
            - Path=/api/product/**
          filters:
            - RewritePath=/api/?(?<segment>.*), /$\{segment}
     #===========================模糊路由=============================
        - id: renren_fast
          uri: lb://renren-fast
          predicates:
            - Path=/api/**
          filters:
            - RewritePath=/api/?(?<segment>.*), /renren-fast/$\{segment}
server:
  port: 88

3.主启动类

@EnableDiscoveryClient
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class GulimallGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(GulimallGatewayApplication.class, args);
    }

}

二、网关统一配置跨域

1. 问题分析:

浏览器不能执行其他网站的脚本,是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制
同源策略:是指协议,域名,端口要相同,任何一个不一样都会产生跨域问题

2.预检请求

发起方发送一个预检请求Request Method: OPTIONS给服务器,获知服务器是否允许该实际请求,可以以这个原理解决跨域问题

3.解决跨域有2种办法

1 通过nginx反向代理服务器

通过nginx代理服务器,暴露一个相同的端口给浏览器,解决了跨域问题,但是如果开发的项目庞大,且每次需要去部署服务器里对nginx做nginx.conf配置,不方便解耦。

2 通过网关配置CorsWebFilter之后,不要加@CrossOrigin

代码

@Configuration
public class GuliMallCorsConfiguration {
    @Bean
    public CorsWebFilter corsWebFilter(){
        //配置跨域
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);  //允许携带cookie

        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsWebFilter(urlBasedCorsConfigurationSource);
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值