首先创建不同环境的配置文件,比如域名和一些常量,创建一个env文件,先看看文件目录
env.dev就是dev环境的域名,.test就是test环境域名,其他同理,然后配置package.json文件
{"name": "require-admin","version": "0.0.0","private": true,"scripts": {"dev": "vite --mode dev","test": "vite build --mode test","prod": "vite build --mode prod","preview": "vite preview"},"dependencies": {"@jridgewell/sourcemap-codec": "^1.4.14","axios": "^1.3.4","element-plus": "^2.3.1","html2canvas": "^1.4.1","pinia": "^2.0.32","vue": "^3.2.47","vue-router": "^4.1.6","vue3-video-play": "^1.3.1-beta.6","vuex": "^4.1.0"},"devDependencies": {"@vitejs/plugin-vue": "^4.0.0","@vitejs/plugin-vue-jsx": "^3.0.0","sass": "^1.60.0","sass-loader": "^13.2.2","vite": "^4.1.4"}
}
scripts里面就是我们的运行配置,当我们执行npm run dev的时候就会读取env.dev文件里面的配置,其他同理,需要运行test环境就用test,最后是我们的接口请求配置文件,
request.js,import.meta.env.VITE_APP_BASE_UR这个就是引用env文件里面的域名了
import axios from "axios";
import {ElMessage
} from 'element-plus'import router from "@/router";
// 创建实例
const instance = axios.create({baseURL: import.meta.env.VITE_APP_BASE_URL, // 请求地址// baseURL: import.meta.env.VITE_APP_BASE_URL, // 请求地址timeout: 10000, // 超时
});
// 拦截器
// 添加请求拦截器
instance.interceptors.request.use(function (config) {// config.url = instance.baseURL + config.url// 在发送请求之前做些什么// if (localStorage.getItem("token")) {// config.headers['Authorization'] = "Bearer " + localStorage.getItem("token"); // 携带token// }// if(getUsername()) {// config.headers['Username'] = getUsername(); // 携带用户名// }return config;
}, function (error) {// 对请求错误做些什么console.log("请求错误", error);return Promise.reject(error);
});
// 添加响应拦截器
instance.interceptors.response.use(function (response) {// 对响应数据做点什么if (response.data.code === 0) {return Promise.resolve(response.data.data);} else {if (response.data.length && response.data.length > 20) {return Promise.resolve(response.data);} else {ElMessage({message: response.data.message,type: "error"})return Promise.reject(data);}}
}, function (error) {console.log("请求失败:", error);const errorData = error.response.data;if (error.response.status == 401) {router.push("/login");// ElMessage({// message: error.response.data.message,// type: "error"// })} else if (errorData.message) {ElMessage({message: errorData.message,type: "error"})} else if (error.response.status == 500) {console.log(500);ElMessage({message: "系统异常",type: "error"})} else if (res.statusCode == 502 || res.statusCode == 503 || res.statusCode == 504) {ElMessage({message: "系统维护中",type: "error"})} else {ElMessage({message: "未知错误",type: error})}// 对响应错误做点什么return Promise.reject(errorData);
});
// 暴露instance
export default instance;