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

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET","HEAD","POST","DELETE","OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
最初的应该是这样的

npm install vue-router@2.8.1

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

引入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
}
}
})

npm install axios --save

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

/**
* HTTP 库
* 存储所有请求
*/
/** 节点测试接口 **/
import InfoApi from "@/api/InfoApi"
export default {
...InfoApi,
}
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)
},
}
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作为与后端网关通信的主要对象,之后的所有验证操作都在此处文件中处理。
对于不需要令牌头的请求,设置白名单放过指定的请求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;
},
}


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