add:配置vite跨域代理,二次封装axios

This commit is contained in:
talktao 2022-03-18 23:29:00 +08:00
parent a7b83f5f63
commit 9b4918a4ab
3 changed files with 96 additions and 18 deletions

View File

@ -1 +1 @@
VUE_APP_baseURL = /
VITE_BASE_URL = 'http://192.168.1.187:8080'

62
src/uitls/request.ts Normal file
View File

@ -0,0 +1,62 @@
/**
* @author TalkTao
* @description
*/
import store from "@/store/index";
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, Method } from "axios";
export interface AxiosResponseProps {
code?: number;
status?: number;
data?: any;
datas?: any;
msg?: string | null;
}
class HttpRequest {
private readonly baseURL: string;
private readonly withCredentials: boolean;
private readonly timeout: number;
constructor() {
this.baseURL = import.meta.env.VITE_BASE_URL as string;
console.log(this.baseURL,'this.baseURL');
this.withCredentials = true;
this.timeout = 1000 * 60;
}
getInitConfig(): AxiosRequestConfig {
return {
baseURL: this.baseURL,
withCredentials: this.withCredentials,
timeout: this.timeout,
};
}
interceptors(instance: AxiosInstance) {
let requestList = [];
const setLoadingToFalse = response => {
requestList
.filter(item => item.url == response.config.url && item.method == response.config.method)
.forEach(item => (item.isLoading = false));
//所有请求都加载完才让加载提示消失
if (requestList.every(item => !item.isLoading)) store.commit("changeIsLoading", false);
};
instance.interceptors.response.use(
response => {
setLoadingToFalse(response);
return response.data;
},
error => {
if (error.response.status == 301) {
store.commit("changeLoginModalVisible", true);
}
setLoadingToFalse(error);
return Promise.reject(error.response?.data);
}
);
}
request(): AxiosInstance {
const instance = axios.create(this.getInitConfig());
this.interceptors(instance);
return instance;
}
}
const http = new HttpRequest();
export default http.request();

View File

@ -1,23 +1,39 @@
import { defineConfig } from 'vite'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from "path"
import styleImport, { VantResolve } from 'vite-plugin-style-import';
// https://vitejs.dev/config/
export default defineConfig({
resolve: {
alias:{
// 配置src目录
"@": path.resolve(__dirname,"src"),
// 导入其他目录
"components": path.resolve(__dirname, "components")
}
},
plugins: [
vue(),
styleImport({
resolves: [VantResolve()],
}),
]
export default defineConfig(({command, mode})=>{
// 检查process.cwd()路径下.env.develeport.local、.env.development、.env.local、.env这四个环境文件
loadEnv(mode, process.cwd())
return {
resolve: {
alias:{
// 配置src目录
"@": path.resolve(__dirname,"src"),
// 导入其他目录
"components": path.resolve(__dirname, "components")
}
},
plugins: [
vue(),
// 配置后Vant各组件才生效
styleImport({
resolves: [VantResolve()],
}),
],
// 跨域代理
server:{
proxy:{
//这里是通过请求/api 来转发到 https://api.pingping6.com/
//假如你要请求https://api.*.com/a/a
//那么axios的url可以配置为 /api/a/a
'/api': 'http://192.168.1.187:8080'
}
}
}
})