谷粒商城-全栈-18 商品服务-三级分类-网关统一配置跨域及分类树型展示

上一节设置了网关路由与重写,但是访问还有问题,会出现跨域问题,下边来看怎么解决跨域问题。

一、配置跨域

1、在网关创建跨域配置文件

创建 gulimall-gateway/src/main/java/com/atguigu/gulimall/gateway/config/GulimallCorsConfiguration.java

package com.atguigu.gulimall.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: kaiyi
 * @create: 2020-08-17 11:47
 */

@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);  // 允许cookie

    source.registerCorsConfiguration("/**", corsConfiguration);
    // 只需要将跨域配置信息放入到该Filter就起作用了
    return new CorsWebFilter(source);
  }
}

2、禁用默认跨域

禁用默认跨域 renren-fast\src\main\java\io\renren\config\CorsConfig.java

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);
////    }
}

二、 三级分类树型展示

1、路由转发

修改gulimall-gateway\src\main\resources\application.yml将路由转发至gulimall-product微服务

spring:
  cloud:
    gateway:
      routes:
        - id: product_route
        uri: lb://gulimall-product
        predicates:
        - Path=/api/product/**
        filters:
        - RewritePath=/api/(?<segment>.*),/$\{segment}

2、创建服务命名空间

在 Nacos 为微服务gulimall-product创建命名空间 gulimall-product

file

3、添加配置中心

添加配置中心 gulimall-product\src\main\resources\bootstrap.properties

spring.application.name=gulimall-product
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.cloud.nacos.config.namespace=748c5710-1166-498b-9e0e-528cb6c9d769

4、添加注册发现功能

添加注册发现功能 gulimall-product\src\main\resources\application.yml

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://192.168.10.10:3306/gulimall_pms
    driver-class-name: com.mysql.cj.jdbc.Driver
  #  配置nacos注册中心
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
mybatis-plus:
  mapper-location: classpath:/mapper/**/*.xml
  global-config:
    db-config:
      id-type: auto  # id主键自增
  configuration:
    # 开启MyBatis的SQL打印
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
server:
  port: 6000

5、启用注册发现功能

启用注册发现功能 gulimall-product\src\main\java\com\atguigu\gulimall\product\GulimallProductApplication.java

// 添加注册发现功能
@EnableDiscoveryClient
@SpringBootApplication
public class GulimallProductApplication {

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

}

6、调整网关路由顺序

由于admin_route 排在 product_route路由前边,当访问product_route,默认会admin_route路由里边的断言判断/api/**,造成需要权限校验,所以,需要把精确的路由配置放在模糊的路由配置前边。

执行调整路由顺序gulimall-gateway\src\main\resources\application.yml

spring:
  cloud:
    gateway:
      routes:
        - id: product_route
          uri: lb://gulimall-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}

前端vue文件 renren-fast-vue\src\views\modules\product\category.vue

<!-- 分类 -->
<template>
  <el-tree :data="menus" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
</template>

<script>
// 这里可以导入其他文件(比如:组件,工具js,第三方插件js,json文件,图片文件等等)
// 例如:import 《组件名称》 from '《组件路径》';

export default {
  // import引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    return {
      menus: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  methods: {
    handleNodeClick(data) {
      console.log(data);
    },
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        this.menus = data.data;
      });
    },
  },
  // 生命周期 - 创建完成(可以访问当前this实例)
  created() {
    this.getMenus();
  },
  // 生命周期 - 挂载完成(可以访问DOM元素)
  mounted() {},
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能,这个函数会触发
};
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类
</style>

访问分类维护页面:http://localhost:8001/#/product-category

file

可以看到三级分类的树形数据已经可以从后台获取并且完美的展示在后端页面了。

为者常成,行者常至