之前配置接口代理总是报404,明明接口地址是对的但还是报是因数写法不对;用了vue2中的写法
pathRewrite改为rewrite
根路径下创建env文件根据自己需要名命
.env.development文件内容
# just a flag
ENV='development'# static前缀
VITE_APP_PUBLIC_PREFIX=""
# 基础模块
VITE_APP_BASIC_PREFIX='/basicSetting'
# 任务模块
VITE_APP_TASK_PREFIX='/task'# 网关
VITE_APP_GATEWAY_PREFIX='/gateway/admin'
# 主题
VITE_APP_THEME=light# vue-cli uses the VITE_CLI_BABEL_TRANSPILE_MODULES environment variable,
# to control whether the babel-plugin-dynamic-import-node plugin is enabled.
# It only does one thing by converting all import() to require().
# This configuration can significantly increase the speed of hot updates,
# when you have a large number of pages.
# Detail: https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/babel-preset-app/index.js
VITE_CLI_BABEL_TRANSPILE_MODULES=true
在vite.config.ts中配置poxy代理
import proxyConfig from './proxy'
const viteConfig = defineConfig(({ mode }) => {return {server: {host: '0.0.0.0', //解决“vite use `--host` to expose”port: 8080,open: true,proxy: proxyConfig}}
})
export default viteConfig
创建proxy.ts文件
import { ProxyOptions } from 'vite'import { loadEnv } from 'vite'const env = loadEnv('development', process.cwd())const proxies: Record<string, ProxyOptions> = {// 任务模块[env.VITE_APP_TASK_PREFIX as string]: {target: 'http://xxx:31249', // 目标地址 --> 服务器地址changeOrigin: true, // 允许跨域rewrite: (path) => path.replace(new RegExp(`^${env.VITE_APP_TASK_PREFIX}`), '')},[env.VITE_APP_GATEWAY_PREFIX as string]: {target: 'http://192.168.8.xx:8080', // 目标地址 --> 服务器地址changeOrigin: true, // 允许跨域rewrite: (path) => path.replace(new RegExp(`^${env.VITE_APP_GATEWAY_PREFIX}`), '')}// 添加其他代理配置
}export default proxies
api.ts接口使用
import request from '@/request/request'
import settings from '@/settings'
export function getTaskList(data: any): Res<any> {return request({url: settings.taskPrefix + '/adm/detectionTasks/page',method: 'post',data})
}
其中的settings.ts文件可以不用封装直接写你的env就行;也可以像我一样封装
export default {/*** 任务模块*/taskPrefix: import.meta.env.VITE_APP_TASK_PREFIX,/*** 网关服务文件前缀*/gatewayPrefix: import.meta.env.VITE_APP_GATEWAY_PREFIX
}
页面中调用接口
import { getTaskList } from '@/api'const param = {entity: {},betweenCondition: {},page: {page: 1,pageSize: 10}}getTaskList(param).then((res) => {console.log(res)}).catch((err) => {console.log(err)})
效果: