在vite.config.ts
文件中添加以下配置
export default defineConfig({
plugins: [vue()],
optimizeDeps: {
include: ['axios'],
},
build: {
target: 'modules',
outDir: 'dist',
assetsDir: 'assets',
minify: 'terser' // 混淆器
},
server: {
cors: true,
open: true,
proxy: {
'/api': {
target: 'http://xxx.xxx.xxx', //代理接口
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
})
在本地项目中新建一个文件夹api
文件夹中编写以下文件
- 配置
axios
(axios.js
)
import axios from "axios"
const instance = axios.create({
baseURL: "/api",
timeout: 5000,
});
// 添加请求拦截器
instance.interceptors.request.use(
(config) => {
// 在发送请求之前做些什么
config.headers["Content-type"] = "application/json";
return config;
},
(error) => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 添加响应拦截器
instance.interceptors.response.use(
(response) => {
// 对响应数据做点什么
// 隐藏加载图
// 获取code
const res = response.data;
// 返回成功
if (res == 200) {
return res;
}
// token 异常
if (res === 508 || res === 512 || res === 514) {
// 登出 清除token缓存
}
return response;
},
(error) => {
// 对响应错误做点什么
return Promise.reject(error);
}
);
export default instance;
- 配置请求(
request.js
)
import instance from "./axios"
const axios = ({
method,
url,
data,
config
}) => {
method = method.toLowerCase();
if (method == 'post') {
return instance.post(url, data, {...config})
} else if (method == 'get') {
return instance.get(url, {
params: data,
...config
})
} else if (method == 'delete') {
return instance.delete(url, {
params: data,
...config
}, )
} else if (method == 'put') {
return instance.put(url, data,{...config})
} else {
console.error('未知的method' + method)
return false
}
}
export default axios
- 配置端口
编写具体的请求,建议按照项目具体情况分文件编写
import axios from "./request"
//请求示例
//get
export const mokeGet = (data) => {
return axios({
url: "/getTest",
method: "get",
data,
config: {
headers: {
'Request-Type': 'wechat'
},
timeout: 3000
}
})
}
post
export const mokePost = (data) => {
return axios({
url: "/postTest",
method: "post",
data,
config: {
headers: {
'Request-Type': 'wechat'
},
timeout: 3000
}
})
}