123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- import axios from "axios";
- import { showMessage } from "./errorStatusCode"; // 引入状态码文件
- import type { AxiosRequestConfig, AxiosResponse, AxiosError } from "axios";
- import { ElNotification } from "element-plus";
- import { useStore } from "../store/index";
- const baseURL = "/api";
- // 创建axios实例
- const instance = axios.create({
- baseURL, // 设置API的基础URL
- });
- // 请求拦截器
- instance.interceptors.request.use(
- (config: AxiosRequestConfig): any => {
- // 可在请求发送前对config进行修改,如添加请求头等
- const { getToken } = useStore();
- const token = getToken;
- const headers = config.headers || {};
- headers["Token"] = token;
- config.headers = headers;
- return config;
- },
- (error: AxiosError) => {
- // 处理请求错误
- return Promise.reject(error);
- }
- );
- // 响应拦截器
- instance.interceptors.response.use(
- (response: AxiosResponse) => {
- // 对响应数据进行处理
- if (response.status !== 200 || response.data.code === 'error') {
- ElNotification.closeAll()
- ElNotification({
- message: response.status !== 200 ? showMessage(response.status) : response.data.msg,
- type: "error",
- });
- }
- return response;
- },
- (error: AxiosError) => {
- ElNotification.closeAll()
- ElNotification({
- message: showMessage(error.request.status), // 传入响应码,匹配响应码对应信息,
- type: "error",
- });
- // 处理响应错误
- return Promise.reject(error);
- }
- );
- // 封装GET请求
- export async function get(url: string, params?: any, file: boolean = false): Promise<any> {
- return new Promise((resolve, reject) => {
- instance
- .get(url, { params })
- .then(({ data }: any) => {
- const { code } = data;
- if (code === "ok" || file) {
- resolve(data);
- return;
- }
- reject(data);
- })
- .catch((error) => {
- reject(error);
- });
- });
- }
- // 封装POST请求
- export async function post(url: string, data?: any): Promise<any> {
- return new Promise((resolve, reject) => {
- instance
- .post(url, data, {
- headers: {
- "Content-type": " application/x-www-form-urlencoded; charset=UTF-8",
- },
- })
- .then(({ data }: any) => {
- const { code } = data;
- if (code === "ok") {
- resolve(data);
- return;
- }
- reject(data);
- })
- .catch((error) => {
- reject(error);
- });
- });
- }
- // 封装文件上传请求
- export async function uploadFile(url: string, data?: any): Promise<any> {
- return new Promise((resolve, reject) => {
- instance
- .post(url, data, {
- headers: {
- "Content-type": "multipart/form-data",
- },
- })
- .then(({ data }: any) => {
- const { code } = data;
- if (code === "ok") {
- resolve(data);
- return;
- }
- reject(data);
- })
- .catch((error) => {
- reject(error);
- });
- });
- }
|