封装请求错误代码提示error-code-type.ts
export const errorCodeType = function(code:string):string{ let errMessage:string = "未知错误" switch (code) { case 400: errMessage = '错误的请求' break case 401: errMessage = '未授权,请重新登录' break case 403: errMessage = '拒绝访问' break case 404: errMessage = '请求错误,未找到该资源' break case 405: errMessage = '请求方法未允许' break case 408: errMessage = '请求超时' break case 500: errMessage = '服务器端出错' break case 501: errMessage = '网络未实现' break case 502: errMessage = '网络错误' break case 503: errMessage = '服务不可用' break case 504: errMessage = '网络超时' break case 505: errMessage = 'http版本不支持该请求' break default: errMessage = `其他连接错误 --${code}` } return errMessage }
封装request.ts
import axios from 'axios'; import { errorCodeType } from '@/script/utils/error-code-type'; import { ElMessage, ElLoading } from 'element-plus'; // 创建axios实例 const service = axios.create({ // 服务接口请求 baseURL: import.meta.env.VITE_APP_BASE_API, // 超时设置 // timeout: 15000, headers:{'Content-Type':'application/json;charset=utf-8'} }) let loading:any; //正在请求的数量 let requestCount:number = 0 //显示loading const showLoading = () => { if (requestCount === 0 && !loading) { //加载中显示样式可以自行修改 loading = ElLoading.service({ text: "拼命加载中,请稍后...", background: 'rgba(0, 0, 0, 0.7)', spinner: 'el-icon-loading', }) } requestCount++; } //隐藏loading const hideLoading = () => { requestCount-- if (requestCount == 0) { loading.close() } } // 请求拦截 service.interceptors.request.use(config => { showLoading() // 是否需要设置 token放在请求头 // config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改 // get请求映射params参数 if (config.method === 'get' && config.params) { let url = config.url + '?'; for (const propName of Object.keys(config.params)) { const value = config.params[propName]; var part = encodeURIComponent(propName) + "="; if (value !== null && typeof(value) !== "undefined") { // 对象处理 if (typeof value === 'object') { for (const key of Object.keys(value)) { let params = propName + '[' + key + ']'; var subPart = encodeURIComponent(params) + "="; url += subPart + encodeURIComponent(value[key]) + "&"; } } else { url += part + encodeURIComponent(value) + "&"; } } } url = url.slice(0, -1); config.params = {}; config.url = url; } return config }, error => { console.log(error) Promise.reject(error) }) // 响应拦截器 service.interceptors.response.use((res:any) => { hideLoading() // 未设置状态码则默认成功状态 const code = res.data['code'] || 200; // 获取错误信息 const msg = errorCodeType(code) || res.data['msg'] || errorCodeType('default') if(code === 200){ return Promise.resolve(res.data) }else{ ElMessage.error(msg) return Promise.reject(res.data) } }, error => { console.log('err' + error) hideLoading() let { message } = error; if (message == "Network Error") { message = "后端接口连接异常"; } else if (message.includes("timeout")) { message = "系统接口请求超时"; } else if (message.includes("Request failed with status code")) { message = "系统接口" + message.substr(message.length - 3) + "异常"; } ElMessage.error({ message: message, duration: 5 * 1000 }) return Promise.reject(error) } ) export default service;
使用axios封装
完整的环境变量配置文件.env.production和.env.development
项目根目录的development文件内容如下
# 开发环境 VITE_APP_TITLE = "阿绵" # 端口号 VITE_APP_PORT = "3000" # 请求接口 VITE_APP_DEV_URL = "http://localhost:8088" # 前缀 VITE_APP_BASE_API = "/api"
项目根目录下的production文件内容如下
# 开发环境 VITE_APP_TITLE = "阿绵" # 端口号 VITE_APP_PORT = "3000" # 请求接口 VITE_APP_DEV_URL = "http://localhost:8088" # 前缀 VITE_APP_BASE_API = "/api"
接口服务封装
import request from "./request"; /** * @description -封装User类型的接口方法 */ export class UserService { // 模块一 /** * @description 用户登录 * @param {string} username - 用户名 * @return {HttpResponse} result */ static async login(data: any) { return request({ url: "/login", method: "post", data, }); } }