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

news2024/10/4 22:58:18

文章目录

  • 前言
  • gatway
    • 网关跨域配置
    • 取消微服务跨域配置
  • 创建vue2项目
    • 准备一个原始vue2项目
      • 安装vue-router
      • 创建路由
      • vue.config.js配置修改
      • App.vue修改
    • 添加接口访问
      • 安装axios
      • 创建request.js
      • 创建index.js
      • 创建InfoApi.js
    • main.js
    • securityUtils.js
  • 前端登录界面
    • 登录
    • 消息提示框
  • 最终效果

前言

一个完整的项目都需要前后端,有些小伙伴会认为,为什么后端依然要学习前端的一些知识?只能说,技多不压身,也是一些必须的内容,因为你在学习的过程中,不免会使用到前端的东西。你总不能找个前端女朋友给你写测试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);
    }
}

取消微服务跨域配置

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

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

创建vue2项目

准备一个原始vue2项目

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

安装vue-router

npm install  vue-router@2.8.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

vue.config.js配置修改

image.png
引入polyfill

 npm i node-polyfill-webpack-plugin

修改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
    }
  }
})

App.vue修改

image.png

<template>
  <div id="app">
    <div class="version-switch">
      <button @click="switchVersion('/')">登录</button>
    </div>
    <router-view></router-view>
  </div>
</template>

<script>

  export default {
    name: 'App',
    components: {},

    methods: {
      switchVersion(path) {
        this.$router.push(path);
      },
    }
  }
</script>

<style>
  #app {
    font-family: Avenir, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    /*color: #2c3e50;*/
    min-height: 100vh; /* 最小高度为视口高度,确保垂直居中 */
  }
  .version-switch {
    width: 100%; /* 宽度设置为100%,独占一整行 */
    height: 2%; /* 宽度设置为100%,独占一整行 */
    margin-top: 20px;
    margin-bottom: 20px;
  }

  .version-switch button {
    padding: 5px 10px;
    margin-right: 5px;
    justify-content: center; /* 水平居中 */
  }
</style>

添加接口访问

安装axios

npm install axios --save

创建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

创建index.js

image.png

/**
 * HTTP 库
 * 存储所有请求
 */

/** 节点测试接口 **/
import InfoApi from "@/api/InfoApi"




export default {
    ...InfoApi,
}

创建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)
    },
}

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')

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;
    },

}

前端登录界面

登录

image.png

<template>
    <div>
        <div>
            <div class="login-form">
                <div>
                    <div>
                        <label>用户名:&nbsp;</label>
                        <input type="text" v-model="login.username">
                    </div>
                    <div>
                        <label >密&nbsp;&nbsp;&nbsp;码:&nbsp;</label>
                        <input type="text" v-model="login.password">
                    </div>
                </div>
            </div>
            <div>
                <button @click="loginApi">用户登录</button>
            </div>
            <div>
                <div class="input-container2">
                    <textarea class="my-input" v-model="token"/>
                </div>
            </div>
        </div>


        <div class="my-container">
            <button class="my-button" @click="oneValue">微服务一测试接口</button>
            <div>
                <textarea class="my-input" v-model="microserviceOneJsonFormData"></textarea>
            </div>
            <div>
                <textarea class="my-input" v-model="microserviceOneJsonData"></textarea>
            </div>
        </div>


        <div class="my-container">
            <button class="my-button" @click="twoValue">微服务二测试接口</button>
            <div>
                <textarea class="my-input" v-model="microserviceTwoJsonData"></textarea>
            </div>
        </div>

    </div>
</template>

<script>

export default {
    name: "loginTest",
    data() {
        return {

            token: "",
            login: {
                username: "fir",
                password: "123",
            },

            // 微服务节点一
            microserviceOneJsonFormData: {
                "msg": "普通的客户端消息",
            },
            microserviceOneJsonData: {},


            // 微服务节点二
            microserviceTwoJsonData: {},
        };
    },

    created() {
        this.jsonString();

        this.connection()
    },

    methods: {


        jsonString() {
            // 将JSON数据转换为字符串
            this.microserviceTwoJsonData = JSON.stringify(this.microserviceTwoJsonData, null, 2);
            this.microserviceOneJsonData = JSON.stringify(this.microserviceOneJsonData, null, 2);
            this.microserviceOneJsonFormData = JSON.stringify(this.microserviceOneJsonFormData, null, 2);

        },

        /**
         * 获取与后端建立通信的必备信息
         */
        loginApi() {
            this.$http.login(this.login).then(res => {
                let code = res.code
                let msg = res.msg
                // let data = res.data
                if (code === 200) {
                    this.$message({message: msg, duration: 1.5, description: ''})
                } else {
                    this.$message({message: "错误", duration: 1.5, description: ''})
                }
            })
        },


        /** 微服务-1 **/
        oneValue() {
            // 在这里可以编写按钮被点击时需要执行的代码

            let data = JSON.parse(this.microserviceOneJsonFormData);

            this.$http.oneGetValue(data).then(res => {
                let msg = res.msg

                let replaceAfter = res;
                replaceAfter = JSON.stringify(replaceAfter, null, 2);
                this.microserviceOneJsonData = replaceAfter;
                this.$message({message: msg, duration: 1.5, description: ''})

            })
        },

        /** 微服务-2 **/
        twoValue() {
            this.$http.twoGetValue().then(res => {
                let msg = res.msg

                let replaceAfter = res
                replaceAfter = JSON.stringify(replaceAfter, null, 2);
                this.microserviceTwoJsonData = replaceAfter;

                this.$message({message: msg, duration: 1.5, description: ''})

            })
        },

    },
}
</script>

<style scoped>


/* 水平布局,且向左浮动 */
.login-form {
    margin-top: 40px;
}

.login-input {
    display: flex;
    flex-direction: row;
}

.login-form > div {
    float: left;
    margin-right: 10px;
}


/* 全局安全痛惜参数-start */
.my-container {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;

    .input-container > label {
        flex: 1;
    }
}

.my-container > button {
    align-self: flex-start;
}

.my-container > .input-container {
    display: flex;
    flex-direction: column;
    align-items: center;
}


.my-input {
    width: 300px; /* 设置输入框的宽度 */
    height: 200px; /* 设置输入框的高度 */
    border: 1px solid #ccc; /* 设置输入框的边框 */
    border-radius: 5px; /* 设置输入框的圆角 */
    padding: 5px; /* 设置输入框的内边距 */
    font-size: 14px; /* 设置输入框的字体大小 */
    color: white; /* 设置输入框的字体颜色为白色 */
    background-color: #434554; /* 设置输入框的背景色 */
    resize: vertical; /* 设置输入框垂直方向可自适应 */
    float: left; /* 将两个元素浮动在左侧 */
    box-sizing: border-box; /* 元素的内边距和边框不会增加元素的宽度 */
}

.my-button {
    float: left; /* 将两个元素浮动在左侧 */
    box-sizing: border-box; /* 元素的内边距和边框不会增加元素的宽度 */
}
</style>

消息提示框

image.png

<template>
    <div class="message-box">
        <div class="message-box__header">{{ message }}</div>
        <div class="message-box__body">{{ description }}</div>
        <button class="message-box__close" @click="close">X</button>
    </div>
</template>

<script>
export default {
    name: "MessageBox",
    props: {
        message: { type: String, default: '' },
        duration: { type: Number, default: 1.5 },
        description: { type: String, default: '' },
    },
    methods: {
        close() {
            this.$emit('close')
        },
    },
    mounted() {
        setTimeout(() => {
            this.close()
        }, this.duration * 1000)
    },
}
</script>

<style scoped>
.message-box {
    position: fixed;
    top: 1%;
    left: 50%;
    transform: translateX(-50%);
    z-index: 9999;
    width: 300px;
    height: 20px;
    padding: 20px;
    background-color: #fff;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.message-box__header {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
}

.message-box__body {
    font-size: 14px;
    line-height: 1.5;
    margin-bottom: 20px;
}

.message-box__close {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 20px;
    height: 20px;
    padding: 0;
    border: none;
    background-color: transparent;
    cursor: pointer;
    font-size: 16px;
    font-weight: bold;
    color: #666;
}
</style>

最终效果

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1613195.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【八股】Spring Boot

SpringBoot是如何实现自动装配的&#xff1f; 首先&#xff0c;SpringBoot的核心注解SpringBootApplication里面包含了三个注解&#xff0c;SpringBootConfigurationEnableAutoConfigurationComponentScan&#xff0c;其中EnableAutoConfiguration是实现自动装配的注解&#x…

VUE运行找不到pinia模块

当我们的VUE运行时报错Module not found: Error: Cant resolve pinia in时 当我们出现这个错误时 可能是 没有pinia模块 此时我们之要下载一下这个模块就可以了 npm install pinia

AD高速板设计-DDR(笔记)

【一】二极管 最高工作频率&#xff1a; 定义&#xff1a;二极管的最高工作频率&#xff0c;即二极管在电路中能够正常工作的最高频率。常见的硅二极管的最高工作频率通常在几十MHz到几百MHz之间。在高频下&#xff0c;二极管可能无法有效地阻止反向电流&#xff0c;但也不会…

C# WPF布局

布局&#xff1a; 1、Grid: <Window x:Class"WpfApp2.MainWindow" xmlns"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x"http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d"http://schemas.microsoft.com…

【大语言模型LLM】-使用大语言模型搭建点餐机器人

关于作者 行业&#xff1a;人工智能训练师/LLM 学者/LLM微调乙方PM发展&#xff1a;大模型微调/增强检索RAG分享国内大模型前沿动态&#xff0c;共同成长&#xff0c;欢迎关注交流… 大语言模型LLM基础-系列文章 【大语言模型LLM】-大语言模型如何编写Prompt?【大语言模型LL…

地质图、地质岩性数据、地质灾害分布、土壤理化性质数据集、土地利用数据、土壤重金属含量分布、植被类型分布

地质图是将沉积岩层、火成岩体、地质构造等的形成时代和相关等各种地质体、地质现象&#xff0c;用一定图例表示在某种比例尺地形图上的一种图件。 是表示地壳表层岩相、岩性、地层年代、地质构造、岩浆活动、矿产分布等的地图的总称。 地质图的编制多以实测资料为基础&#xf…

Eclipse+Java+Swing实现学生信息管理系统-TXT存储信息

一、系统介绍 1.开发环境 操作系统&#xff1a;Win10 开发工具 &#xff1a;Eclipse2021 JDK版本&#xff1a;jdk1.8 存储方式&#xff1a;Txt文件存储 2.技术选型 JavaSwingTxt 3.功能模块 4.工程结构 5.系统功能 1.系统登录 管理员可以登录系统。 2.教师-查看学生…

初学者如何选择ARM开发硬件?

1&#xff0e; 如果你有做硬件和单片机的经验,建议自己做个最小系统板&#xff1a;假如你从没有做过ARM的开发&#xff0c;建议你一开始不要贪大求全&#xff0c;把所有的应用都做好&#xff0c;因为ARM的启动方式和dsp或单片机有所不同&#xff0c;往往会碰到各种问题&#xf…

【天龙怀旧服】攻略day7

关键字&#xff1a; 新星1.49、金针渡劫、10灵 1】新星&#xff08;苍山破煞&#xff09; 周三周六限定副本&#xff0c;19.00-24.00 通常刷1.49w&#xff0c;刷149点元佑碎金 boss选择通常为狂鬼难度&#xff0c;八风不动即放大不选&#xff0c;第二排第一个也不选&#xf…

【Hadoop】- MapReduce YARN的部署[8]

目录 一、部署说明 二、集群规划 三、MapReduce配置文件 四、YARN配置文件 五、分发配置文件 六、集群启动命令 七、查看YARN的WEB UI 页面 一、部署说明 Hadoop HDFS分布式文件系统&#xff0c;我们会启动&#xff1a; NameNode进程作为管理节点DataNode进程作为工作节…

lua整合redis

文章目录 lua基础只适合lua连接操作redis1.下载lua依赖2.导包,连接3.常用的命令1.set,get,push命令 2.自增管道命令命令集合4.使用redis操作lua1.实现秒杀功能synchronized关键字 分布式锁 lua 基础只适合 1.编译 -- 编译 luac a.lua -- 运行 lua a.lua2.命名规范 -- 多行注…

【Hadoop】- MapReduce YARN 初体验[9]

目录 提交MapReduce程序至YARN运行 1、提交wordcount示例程序 1.1、先准备words.txt文件上传到hdfs&#xff0c;文件内容如下&#xff1a; 1.2、在hdfs中创建两个文件夹&#xff0c;分别为/input、/output 1.3、将创建好的words.txt文件上传到hdfs中/input 1.4、提交MapR…

Dynamic Wallpaper for Mac激活版:视频动态壁纸软件

Dynamic Wallpaper for Mac 是一款为Mac电脑量身打造的视频动态壁纸应用&#xff0c;为您的桌面带来无限生机和创意。这款应用提供了丰富多样的视频壁纸选择&#xff0c;涵盖了自然风景、抽象艺术、科幻奇观等多种主题&#xff0c;让您的桌面成为一幅活生生的艺术画作。 Dynami…

ES中文检索须知:分词器与中文分词器

ElasticSearch (es)的核心功能即为数据检索&#xff0c;常被用来构建内部搜索引擎或者实现大规模数据在推荐召回流程中的粗排过程。 ES分词 分词即为将doc通过Analyzer切分成一个一个Term&#xff08;关键字&#xff09;&#xff0c;es分词在索引构建和数据检索时均有体现&…

(避雷指引:管理页面超时问题)windows下载安装RabbitMQ

一、背景&#xff1a; 学习RabbitMQ过程中&#xff0c;由于个人电脑性能问题&#xff0c;直接装在windows去使用RabbitMQ&#xff0c;根据各大网友教程&#xff0c;去下载安装完之后&#xff0c;使用web端进行简单的入门操作时&#xff0c;总是一直提示超时&#xff0c;要么容…

【项目】仿muduo库One Thread One Loop式主从Reactor模型实现高并发服务器(TcpServer板块)

【项目】仿muduo库One Thread One Loop式主从Reactor模型实现⾼并发服务器&#xff08;TcpServer板块&#xff09; 一、思路图二、模式关系图三、定时器的设计1、Linux本身给我们的定时器2、我们自己实现的定时器&#xff08;1&#xff09;代码部分&#xff08;2&#xff09;思…

图论——基础概念

文章目录 学习引言什么是图图的一些定义和概念图的存储方式二维数组邻接矩阵存储优缺点 数组模拟邻接表存储优缺点 边集数组优缺点排序前向星优缺点链式前向星优缺点 学习引言 图论&#xff0c;是 C 里面很重要的一种算法&#xff0c;今天&#xff0c;就让我们一起来了解一下图…

使用docker搭建GitLab个人开发项目私服

一、安装docker 1.更新系统 dnf update # 最后出现这个标识就说明更新系统成功 Complete!2.添加docker源 dnf config-manager --add-repohttps://download.docker.com/linux/centos/docker-ce.repo # 最后出现这个标识就说明添加成功 Adding repo from: https://download.…

【数据结构】顺序表:与时俱进的结构解析与创新应用

欢迎来到白刘的领域 Miracle_86.-CSDN博客 系列专栏 数据结构与算法 先赞后看&#xff0c;已成习惯 创作不易&#xff0c;多多支持&#xff01; 目录 一、数据结构的概念 二、顺序表&#xff08;Sequence List&#xff09; 2.1 线性表的概念以及结构 2.2 顺序表分类 …

SpringMVC深解--一起学习吧之架构

SpringMVC的工作原理主要基于请求驱动&#xff0c;它采用了前端控制器模式来进行设计。以下是SpringMVC工作原理的详细解释&#xff1a; 请求接收与分发&#xff1a; 当用户发送一个请求到Web服务器时&#xff0c;这个请求首先会被SpringMVC的前端控制器&#xff08;Dispatche…