程序员的资源宝库

网站首页 > gitee 正文

第十三章第五节:网关服务配置全局跨域

sanyeah 2024-04-13 16:07:32 gitee 3 ℃ 0 评论

1、创建网关服务的跨域配置类

com.applesnt.onlinemall.gateway下创建config包
在config包下创建MallCorsConfiguration.javap配置类

package com.applesnt.onlinemall.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * @author menghaibin
 * @project onlinemall
 * @date 2021/6/3-21:01
 * @describe 跨域配置类
 */
//这是一个配置类
@Configuration
public class MallCorsConfiguration {
    //加入到spring容器中
    @Bean
    public CorsWebFilter corsWebFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration configuration = new CorsConfiguration();
        //允许所有请求头
        configuration.addAllowedHeader("*");
        //允许所有请求方式
        configuration.addAllowedMethod("*");
        //允许所有请求来源
        configuration.addAllowedOrigin("*");
        //运行携带cookie跨越
        configuration.setAllowCredentials(true);

        source.registerCorsConfiguration("/**",configuration);
        return new CorsWebFilter(source);
    }
}

2、去掉renren-fast项目中跨域配置,不然会加载两次配置

io.renren.config.CorsConfig

package io.renren.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

//    @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        registry.addMapping("/**")
//            .allowedOrigins("*")
//            .allowCredentials(true)
//            .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
//            .maxAge(3600);
//    }
}

3、重启相关服务,登录成功后,获取tree数据时会报以下错误

http://localhost:88/api/product/category/list/tree 这个请求并非获取分类数据的请求
正确的请求应该是:
http://localhost:88/product/category/list/tree
所以需求在geteway中配置路由规则

4、配置访问产品获取分类服务相关的路由规则

获取分类的路由配置优先级高于renren-fast的规则,否则/api的路由会拦截/api/product的请求
    #配置renren-fast的网关路由
    gateway:
      routes:
#        分类维护的路由配置
        - id: product_route
          uri: lb://onlinemall-product
          predicates:
            - Path=/api/product/**
          filters:
            - RewritePath=/api/(?<segment>.*), /$\{segment}
#        获取验证码的路由配置
        - id: admin_route
          uri: lb://renren-fast
          predicates:
            - Path=/api/**
          filters:
            - RewritePath=/api/(?<segment>.*), /renren-fast/$\{segment}

5、重启相关服务访问成功

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表