feat: 全局后端请求增加 /api 方便vite 代理配置

This commit is contained in:
lbw 2023-04-06 14:38:45 +08:00
parent c38b355b18
commit 69403bfc0c
12 changed files with 44 additions and 26 deletions

20
.env
View File

@ -1,6 +1,18 @@
# 是否是微服务架构(重要) # 是否是微服务架构(重要)
VITE_IS_MICRO= false VITE_IS_MICRO= false
# 前端访问前缀
VITE_PUBLIC_PATH = /
# 后端请求前缀
VITE_API_URL = /api
# ADMIN 服务地址
VITE_ADMIN_PROXY_PATH = http://localhost:9999
# 代码生成服务地址 (单体架构有效)
VITE_GEN_PROXY_PATH = http://localhost:5003
# 前端加密密钥 # 前端加密密钥
VITE_PWD_ENC_KEY='pigxpigxpigxpigx' VITE_PWD_ENC_KEY='pigxpigxpigxpigx'
@ -13,11 +25,6 @@ VITE_OAUTH2_MOBILE_CLIENT='app:app'
# OAUTH2 社交登录客户端信息 # OAUTH2 社交登录客户端信息
VITE_OAUTH2_SOCIAL_CLIENT='social:social' VITE_OAUTH2_SOCIAL_CLIENT='social:social'
# ADMIN 服务地址
VITE_ADMIN_PROXY_PATH = http://localhost:9999
# 代码生成服务地址
VITE_GEN_PROXY_PATH = http://localhost:5003
# 是否开启websocket 消息接受, # 是否开启websocket 消息接受,
VITE_WEBSOCKET_ENABLE = false VITE_WEBSOCKET_ENABLE = false
@ -28,6 +35,3 @@ VITE_REGISTER_ENABLE = true
# 是否开启租户自动选择 (根据租户域名) # 是否开启租户自动选择 (根据租户域名)
VITE_AUTO_TENANT = false VITE_AUTO_TENANT = false
# 代码代码前缀
VITE_PUBLIC_PATH = /

View File

@ -10,14 +10,17 @@ import { useUserInfo } from '/@/stores/userInfo';
export const login = (data: any) => { export const login = (data: any) => {
const basicAuth = 'Basic ' + window.btoa(import.meta.env.VITE_OAUTH2_PASSWORD_CLIENT); const basicAuth = 'Basic ' + window.btoa(import.meta.env.VITE_OAUTH2_PASSWORD_CLIENT);
Session.set('basicAuth', basicAuth); Session.set('basicAuth', basicAuth);
const { username, password, randomStr, code, grant_type, scope } = data;
return request({ return request({
url: '/auth/oauth2/token', url: '/auth/oauth2/token',
method: 'post', method: 'post',
params: data, params: { username, randomStr, code, grant_type, scope },
data: { password: password },
headers: { headers: {
skipToken: true, skipToken: true,
'TENANT-ID': '1', 'TENANT-ID': '1',
Authorization: basicAuth, Authorization: basicAuth,
'Content-Type': 'application/x-www-form-urlencoded',
}, },
}); });
}; };
@ -34,6 +37,7 @@ export const loginByMobile = (mobile: any, code: any) => {
skipToken: true, skipToken: true,
'TENANT-ID': '1', 'TENANT-ID': '1',
Authorization: basicAuth, Authorization: basicAuth,
'Content-Type': 'application/x-www-form-urlencoded',
}, },
method: 'post', method: 'post',
params: { mobile: 'SMS@' + mobile, code: code, grant_type, scope }, params: { mobile: 'SMS@' + mobile, code: code, grant_type, scope },
@ -52,6 +56,7 @@ export const loginBySocial = (state: string, code: string) => {
skipToken: true, skipToken: true,
'TENANT-ID': '1', 'TENANT-ID': '1',
Authorization: basicAuth, Authorization: basicAuth,
'Content-Type': 'application/x-www-form-urlencoded',
}, },
method: 'post', method: 'post',
params: { mobile: state + '@' + code, code: code, grant_type, scope }, params: { mobile: state + '@' + code, code: code, grant_type, scope },
@ -60,7 +65,7 @@ export const loginBySocial = (state: string, code: string) => {
export const sendMobileCode = (mobile: any) => { export const sendMobileCode = (mobile: any) => {
return request({ return request({
url: '/auth/mobile/' + mobile, url: '/admin/mobile/' + mobile,
method: 'get', method: 'get',
}); });
}; };
@ -77,6 +82,7 @@ export const refreshTokenApi = (refresh_token: string) => {
skipToken: true, skipToken: true,
'TENANT-ID': '1', 'TENANT-ID': '1',
Authorization: basicAuth, Authorization: basicAuth,
'Content-Type': 'application/x-www-form-urlencoded',
}, },
method: 'post', method: 'post',
params: { refresh_token, grant_type, scope }, params: { refresh_token, grant_type, scope },
@ -94,6 +100,7 @@ export const checkToken = (refreshTime: number, refreshLock: boolean) => {
headers: { headers: {
skipToken: true, skipToken: true,
Authorization: basicAuth, Authorization: basicAuth,
'Content-Type': 'application/x-www-form-urlencoded',
}, },
method: 'get', method: 'get',
params: { token: Session.getToken() }, params: { token: Session.getToken() },
@ -131,7 +138,7 @@ export const checkToken = (refreshTime: number, refreshLock: boolean) => {
*/ */
export const getUserInfo = () => { export const getUserInfo = () => {
return request({ return request({
url: '/auth/user/info', url: '/admin/user/info',
method: 'get', method: 'get',
}); });
}; };

View File

@ -6,7 +6,7 @@
:limit="1" :limit="1"
accept=".xlsx, .xls" accept=".xlsx, .xls"
:headers="headers" :headers="headers"
:action="other.adaptationUrl(url)" :action="baseURL + other.adaptationUrl(url)"
:disabled="state.upload.isUploading" :disabled="state.upload.isUploading"
:on-progress="handleFileUploadProgress" :on-progress="handleFileUploadProgress"
:on-success="handleFileSuccess" :on-success="handleFileSuccess"

View File

@ -15,7 +15,7 @@
:accept="fileType.join(',')" :accept="fileType.join(',')"
> >
<template v-if="imageUrl"> <template v-if="imageUrl">
<img :src="imageUrl" class="upload-image" /> <img :src="baseURL + imageUrl" class="upload-image" />
<div class="upload-handle" @click.stop> <div class="upload-handle" @click.stop>
<div class="handle-icon" @click="editImg" v-if="!self_disabled"> <div class="handle-icon" @click="editImg" v-if="!self_disabled">
<el-icon><Edit /></el-icon> <el-icon><Edit /></el-icon>

View File

@ -4,7 +4,7 @@
<el-upload <el-upload
ref="fileUpload" ref="fileUpload"
v-if="props.type === 'default'" v-if="props.type === 'default'"
:action="other.adaptationUrl(props.uploadFileUrl)" :action="baseURL + other.adaptationUrl(props.uploadFileUrl)"
:before-upload="handleBeforeUpload" :before-upload="handleBeforeUpload"
:file-list="fileList" :file-list="fileList"
:headers="headers" :headers="headers"

View File

@ -7,7 +7,7 @@ import request from '/@/utils/request';
//获取验证图片 以及token //获取验证图片 以及token
export function reqGet(data: Object) { export function reqGet(data: Object) {
return request({ return request({
url: '/admin/code/create', url: '/code/create',
method: 'get', method: 'get',
data, data,
}); });
@ -16,7 +16,7 @@ export function reqGet(data: Object) {
//滑动或者点选验证 //滑动或者点选验证
export function reqCheck(data: Object) { export function reqCheck(data: Object) {
return request({ return request({
url: '/admin/code/check', url: '/code/check',
method: 'post', method: 'post',
params: data, params: data,
}); });

View File

@ -47,7 +47,7 @@
</div> </div>
<el-dropdown :show-timeout="70" :hide-timeout="50" @command="onHandleCommandClick"> <el-dropdown :show-timeout="70" :hide-timeout="50" @command="onHandleCommandClick">
<span class="layout-navbars-breadcrumb-user-link"> <span class="layout-navbars-breadcrumb-user-link">
<img :src="userInfos.user.avatar" class="layout-navbars-breadcrumb-user-link-photo mr5" /> <img :src="baseURL + userInfos.user.avatar" class="layout-navbars-breadcrumb-user-link-photo mr5" />
{{ userInfos.user.username }} {{ userInfos.user.username }}
<el-icon class="el-icon--right"> <el-icon class="el-icon--right">
<ele-ArrowDown /> <ele-ArrowDown />

View File

@ -46,6 +46,7 @@ app.config.globalProperties.parseDate = parseDate;
app.config.globalProperties.dateTimeStr = dateTimeStr; app.config.globalProperties.dateTimeStr = dateTimeStr;
app.config.globalProperties.dateStr = dateStr; app.config.globalProperties.dateStr = dateStr;
app.config.globalProperties.timeStr = timeStr; app.config.globalProperties.timeStr = timeStr;
app.config.globalProperties.baseURL = import.meta.env.VITE_API_URL;
directive(app); directive(app);
other.elSvg(app); other.elSvg(app);

View File

@ -47,7 +47,7 @@ export const useUserInfo = defineStore('userInfo', {
resolve(res); resolve(res);
}) })
.catch((err) => { .catch((err) => {
useMessage().error('服务器异常,请联系管理员'); useMessage().error(err?.msg || '系统异常请联系管理员');
reject(err); reject(err);
}); });
}); });
@ -70,7 +70,7 @@ export const useUserInfo = defineStore('userInfo', {
resolve(res); resolve(res);
}) })
.catch((err) => { .catch((err) => {
useMessage().error(err.msg); useMessage().error(err?.msg || '系统异常请联系管理员');
reject(err); reject(err);
}); });
}); });
@ -94,7 +94,7 @@ export const useUserInfo = defineStore('userInfo', {
resolve(res); resolve(res);
}) })
.catch((err) => { .catch((err) => {
useMessage().error('登录失败,账号未绑定'); useMessage().error(err?.msg || '系统异常请联系管理员');
reject(err); reject(err);
}); });
}); });

View File

@ -458,10 +458,15 @@ export function toUnderline(str: string) {
const adaptationUrl = (originUrl?: string) => { const adaptationUrl = (originUrl?: string) => {
// 微服务架构 不做路径转换,为空不做路径转换 // 微服务架构 不做路径转换,为空不做路径转换
const isMicro = import.meta.env.VITE_IS_MICRO; const isMicro = import.meta.env.VITE_IS_MICRO;
if (validateNull(isMicro) || isMicro === true) { if (validateNull(isMicro) || isMicro === 'true') {
return originUrl; return originUrl;
} }
// 验证码服务
if (originUrl?.startsWith('/code/')) {
return `/admin/${originUrl}`;
}
// 如果是代码生成服务,不做路径转换 // 如果是代码生成服务,不做路径转换
if (originUrl?.startsWith('/gen')) { if (originUrl?.startsWith('/gen')) {
return originUrl; return originUrl;

View File

@ -10,7 +10,6 @@ import other from './other';
const service: AxiosInstance = axios.create({ const service: AxiosInstance = axios.create({
baseURL: import.meta.env.VITE_API_URL, baseURL: import.meta.env.VITE_API_URL,
timeout: 50000, // 全局超时时间 timeout: 50000, // 全局超时时间
headers: { 'Content-Type': 'application/json' },
}); });
/** /**

View File

@ -53,15 +53,17 @@ const viteConfig = defineConfig((mode: ConfigEnv) => {
hmr: true, // 启用热更新 hmr: true, // 启用热更新
proxy: { proxy: {
// 代理设置,用于解决跨域问题 // 代理设置,用于解决跨域问题
'/admin': { '/api': {
target: env.VITE_ADMIN_PROXY_PATH, // 目标服务器地址 target: env.VITE_ADMIN_PROXY_PATH, // 目标服务器地址
ws: true, // 是否启用 WebSocket ws: true, // 是否启用 WebSocket
changeOrigin: true, // 是否修改请求头中的 Origin 字段 changeOrigin: true, // 是否修改请求头中的 Origin 字段
rewrite: (path) => path.replace(/^\/api/, ''),
}, },
'/gen': { '/api/gen': {
target: env.VITE_GEN_PROXY_PATH, //单体架构下特殊处理代码生成模块代理
ws: true, target: env.VITE_IS_MICRO === 'true' ? env.VITE_ADMIN_PROXY_PATH : env.VITE_GEN_PROXY_PATH,
changeOrigin: true, changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
}, },
}, },
}, },