• [Spring Cloud] (4)搭建Vue2与网关、微服务通信并配置跨域


    前言

    一个完整的项目都需要前后端,有些小伙伴会认为,为什么后端依然要学习前端的一些知识?只能说,技多不压身,也是一些必须的内容,因为你在学习的过程中,不免会使用到前端的东西。你总不能找个前端女朋友给你写测试demo吧?所以只能自力更生。。。
    本文就从零搭建一个前端项目,以配合后端的各种拦截器的处理规则。(前端有些地方可能处理的不好,敬请见谅)
    本文gateway,微服务,vue已开源到gitee
    杉极简/gateway网关阶段学习

    gatway

    网关跨域配置

    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;
    import org.springframework.web.util.pattern.PathPatternParser;
    
    @Configuration
    public class CorsConfig {
        @Bean
        public CorsWebFilter corsFilter() {
            CorsConfiguration config = new CorsConfiguration();
            config.addAllowedMethod("*");
            config.addAllowedOrigin("*");
            config.addAllowedHeader("*");
    
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
            source.registerCorsConfiguration("/**", config);
    
            return new CorsWebFilter(source);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    取消微服务跨域配置

    注释删除微服务的跨域,否则会使跨域失效(网关与微服务不能同时开启跨域)
    image.png

        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOriginPatterns("*")
                    .allowedMethods("GET","HEAD","POST","DELETE","OPTIONS")
                    .allowCredentials(true)
                    .maxAge(3600)
                    .allowedHeaders("*");
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    创建vue2项目

    准备一个原始vue2项目

    最初的应该是这样的
    image.png

    安装vue-router

    npm install  vue-router@2.8.1
    
    • 1

    创建路由

    image.png

    import Router from 'vue-router'
    import Vue from "vue";
    import loginTest from "@/views/loginTest.vue";
    
    Vue.use(Router)
    
    const routes = [
      {
        path: '/',
        name: 'login',
        component: loginTest
      },
    ]
    
    
    const router = new Router({
      mode: 'history',
      base: process.env.BASE_URL,
      routes: routes
    })
    
    export default router
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    vue.config.js配置修改

    image.png
    引入polyfill

     npm i node-polyfill-webpack-plugin
    
    • 1

    修改vue.config.js

    const { defineConfig } = require('@vue/cli-service')
    // 引入polyfill
    const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
    
    module.exports = defineConfig({
      transpileDependencies: true,
      // 引入polyfill
      configureWebpack: {
        plugins: [
          new NodePolyfillPlugin({})
        ]
      },
      devServer: {
        client: {
          overlay: false
        }
      }
    })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    App.vue修改

    image.png

    
    
    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    添加接口访问

    安装axios

    npm install axios --save
    
    • 1

    创建request.js

    image.png

    import axios from 'axios'
    
    //引入axios
    // 动态获取本机ip,作为连接后台服务的地址,但访问地址不能是localhost
    // 为了灵活配置后台地址,后期需要更改为,配置文件指定字段决定优先使用配置ip还是自己生产的ip(如下)
    const hostPort = document.location.host;
    const hostData = hostPort.split(":")
    const host = hostData[0];
    
    //axios.create能创造一个新的axios实例
    const server = axios.create({
        baseURL: "http" + "://" + host + ":51001", //配置请求的url
        timeout: 6000, //配置超时时间
        headers: {
            'Content-Type': "application/x-www-form-urlencoded",
        }, //配置请求头
    
    })
    
    
    
    
    /** 请求拦截器 **/
    server.interceptors.request.use(function (request) {
        // 非白名单的请求都加上一个请求头
    
        return request;
    }, function (error) {
        return Promise.reject(error);
    });
    
    
    /** 响应拦截器 **/
    server.interceptors.response.use(function (response) {
        return response.data;
    }, function (error) {
        // axios请求服务器端发生错误的处理
        return Promise.reject(error);
    });
    
    
    
    /**
     * 定义一个函数-用于接口
     * 利用我们封装好的request发送请求
     * @param url 后台请求地址
     * @param method 请求方法(get/post...)
     * @param obj 向后端传递参数数据
     * @returns AxiosPromise 后端接口返回数据
     */
    export function dataInterface(url, method, obj) {
        return server({
            url: url,
            method: method,
            params: obj
        })
    }
    
    
    export default server
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61

    创建index.js

    image.png

    /**
     * HTTP 库
     * 存储所有请求
     */
    
    /** 节点测试接口 **/
    import InfoApi from "@/api/InfoApi"
    
    
    
    
    export default {
        ...InfoApi,
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    创建InfoApi.js

    import {dataInterface} from "@/utils/request";
    
    export default {
    
        /** 系统登陆接口 **/
        login(obj) {
            return dataInterface("/auth/login","get", obj)
        },
    
        oneGetValue(obj){
            return dataInterface("/api-one/getValue", "get", obj)
        },
    
    
        twoGetValue(obj){
            return dataInterface("/api-two/getValue", "get", obj)
        },
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    main.js

    import Vue from 'vue'
    import App from './App.vue'
    import router from './router'
    import http from "@/api/index";
    import securityUtils from "@/utils/securityUtils";
    
    Vue.config.productionTip = false
    
    Vue.prototype.$http = http;
    Vue.prototype.$securityUtils = securityUtils;
    
    
    import MessageBox from './components/MessageBox.vue'
    
    Vue.component('MessageBox', MessageBox)
    
    // 将 MessageBox 组件挂载到 Vue.prototype 上
    Vue.prototype.$message = function ({ message, duration, description }) {
      const MessageBoxComponent = Vue.extend(MessageBox)
    
      const instance = new MessageBoxComponent({
        propsData: { message, duration, description }
      })
    
      const vm = instance.$mount()
      document.body.appendChild(vm.$el)
    
      setTimeout(() => {
        document.body.removeChild(vm.$el)
        vm.$destroy()
      }, duration * 1000)
    }
    
    // 在组件中使用 this.$message
    // this.$message({ message: 'Hello world!', duration: 1.5, description: '' })
    
    
    new Vue({
      router,
      render: h => h(App),
    }).$mount('#app')
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    securityUtils.js

    image.png
    securityUtils作为与后端网关通信的主要对象,之后的所有验证操作都在此处文件中处理。
    对于不需要令牌头的请求,设置白名单放过指定的请求whiteList
    对于普通的数据接口,需要增加令牌Authorization以通过后端的请求校验。

    /** 全局变量配置-start **/
    
    // url白名单设置
    const whiteList = [
        "/tick/auth/login",
    ]
    
    /** 全局变量配置-end **/
    
    
    
    export default {
    
    
        /**
         * 读取信息
         */
        get(key) {
            return sessionStorage.getItem(key)
        },
        
        
        /**
         * 添加信息
         */
        set(key, value) {
            sessionStorage.setItem(key, value)
        },
    
    
        /**
         * 登录之后进行处理
         */
        loginDeal(token){
            this.set("token", token)
        },
    
    
    
        /**
         * gateway网关验证信息处理(请求头)
         */
        gatewayRequest(config) {
            let key = true;
            whiteList.find(function (value) {
                if (value === config.url) {
                    key = false;
                }
            });
    
            // 对非白名单请求进行处理
            if (key) {
                // 请求体数据
                let token = this.get("token")
    
                // 请求中增加token
                if (token) {
                    config.headers.Authorization = token;
                }
            }
    
            return config;
        },
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65

    前端登录界面

    登录

    image.png

    
    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202

    消息提示框

    image.png

    
    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70

    最终效果

    此时我们需要先登录,之后就可以正常访问微服务。
    image.png此时如果不登陆就直接访问数据接口的话,则会提示登录过期,无法获取数据。
    image.png

  • 相关阅读:
    一次清理全屋地面,一键清洁烘干无异味,KEEWOO启为C260 Pro洗地机上手
    Spring-AOP 讲解
    【web安全】Nodejs原型链污染分析
    将 List 转换为 String
    【Node.js】session认证原理和JWT认证原理
    提高代码质量!详解在Gradle项目中使用PMD的正确姿势
    Kafka实现高性能消息队列分析
    linux golang安装
    opencv c++ 实时对象追踪
    C++ 初识函数模板
  • 原文地址:https://blog.csdn.net/qq_46554590/article/details/138050518