欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

网关

程序员文章站 2022-06-03 19:07:51
...

配置网关以及解决跨域问题

​ 1、首先在前端页面,把基础请求路由给网关

  // api接口请求地址
  window.SITE_CONFIG['baseUrl'] = 'http://localhost:88/api';

​ 2、在网关中首先引入依赖

		<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
		<dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.1.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
            <version>2.1.0.RELEASE</version>
        </dependency>

​ 3、将网关注册到nacos

//spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
//spring.application.name=container-gateway
//server.port=88
@EnableDiscoveryClient
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class ContainerGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(ContainerGatewayApplication.class, args);
    }

}

​ 4、在application.yml文件中配置路由

spring:
  cloud:
    gateway:
      routes:
        - id: admin_route
          uri: lb://renren-fast
          predicates:
            - Path=/api/**
            #这里是指以/api开头的所有请求全部进行拦截
          filters:
            - RewritePath=/api/(?<segment>.*),/renren-fast/$\{segment}
            #对路径进行重写

​ 5、编写配置类,对跨域问题进行处理

@Configuration
public class ContainerOrgConfiguration {
    @Bean
    public CorsWebFilter corsWebFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration=new CorsConfiguration();
//        1、配置跨域
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);
        source.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsWebFilter(source);
    }
}

相关标签: java gateway

上一篇: zuul网关

下一篇: 网关