vue3 原生请求封装 我这里用一个案例来解释
需求:把vue3原生的静态页 集成到 vue2 的若依项目 并且可以访问 vue2接口
在vue3 src 下的 utils 下 创建文件request.ts文件
import axios from "axios";
import { showMessage } from "./status"; // 引入状态码
import { ElMessage } from "element-plus"; // 引入提示框// 设置接口超时时间
axios.defaults.timeout = 60000;
axios.defaults.baseURL = "/dev-api" || ""; // 自定义接口地址const token = () => {if (sessionStorage.getItem("token")) {return sessionStorage.getItem("token");} else {return sessionStorage.getItem("token");}
};const getCookie = (name) => {const value = `; ${document.cookie}`;const parts = value.split(`; ${name}=`);if (parts.length === 2) return parts.pop().split(';').shift();
};//请求拦截
axios.interceptors.request.use((config) => {// 配置请求头config.headers["Content-Type"] = "application/json;charset=UTF-8";config.headers["token"] = token();//配置令牌等return config;},(error) => {return Promise.reject(error);}
);// 响应拦截
axios.interceptors.response.use((response) => {return response;},(error) => {const { response } = error;if (response) {// 请求已发出,但是不在2xx的范围showMessage(response.status); // 传入响应码,匹配响应码对应信息return Promise.reject(response.data);} else {ElMessage.warning("网络连接异常,请稍后再试!");}}
);//请求并导出
export function request(data: any) {return new Promise((resolve, reject) => {const promise = axios(data);//处理返回promise.then((res: any) => {resolve(res.data);}).catch((err: any) => {reject(err.data);});});
}
同级包下 新建状态码文件 status.ts
export const showMessage = (status: number | string): string => {let message: string = "";switch (status) {case 400:message = "请求错误(400)";break;case 401:message = "未授权,请重新登录(401)";break;case 403:message = "拒绝访问(403)";break;case 404:message = "请求出错(404)";break;case 408:message = "请求超时(408)";break;case 500:message = "服务器错误(500)";break;case 501:message = "服务未实现(501)";break;case 502:message = "网络错误(502)";break;case 503:message = "服务不可用(503)";break;case 504:message = "网络超时(504)";break;case 505:message = "HTTP版本不受支持(505)";break;default:message = `连接出错(${status})!`;}return `${message},请检查网络或联系管理员!`;
};
配置代理
注意放置位置
const proxy = {'/dev-api': {target: 'http://localhost:80', // 实际请求地址changeOrigin: true,rewrite: (path) => path.replace(/^/dev-api/, ''),},
};server: {proxy,host: 'localhost',port: 80,open: true,},
本次案例使用 api下创建login.ts文件 (login名称未修改)
请求名称未修改
import { request } from "../utils/request";export function login(data: any) {return request({url: "/system/encipher",method: "get",data,});
}export function list(params: any) {return request({url: "/system/encipher/",method: "get",params,});
}
在对应vue中 点击事件中使用
const onRootClick = () => {var data = localStorage.getItem("datalist");var item = JSON.parse(data);var clinetIds;for (const itemElement of item) {if(itemElement.name==props.name){clinetIds = itemElement.clientId}}var userName = localStorage.getItem("username");list({userName: userName, clientId: clinetIds}).then((res: any) => {//执行后续}).catch(() =>{alert("请求错误")})
};