vue3+ts+axios封装

需要安装 axios,qs
yarn add axios
npm i axios 
cnpm i axios
yarn add qs
npm i qs
cnpm i qs

在src/API/axios.ts

 

import axios from 'axios';
import qs from "qs";

axios.defaults.baseURL = "/api";    //  请求地址统一配置到vite.config.ts中代理
axios.defaults.headers.post["Content-Type"] = "application/json";
// axios.defaults.headers.post["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.timeout = 20000; //设置请求超时时间

// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    // 可以在这里添加请求头、认证token等
    // 例如:config.headers['Authorization'] = 'Bearer ' + token;
    return config;
  },
  (error: any) => {
    // 请求错误处理
    return Promise.reject(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error: any) => {
    // 响应错误处理
    return Promise.reject(error);
  }
);

interface ApiResponse<T = any> {
  code: number;
  data: T | null;
  [key: string]: any;
}

function checkStatus(response: any): Promise<ApiResponse> {
  return new Promise((resolve, reject) => {
    if (!response) {
      reject(new Error('响应对象为空'));
      return;
    }

    const { status, data } = response;

    try {
      if (status === 200 || status === 304) {
        // 成功状态
        resolve(data as ApiResponse);
      } else if (status >= 400 && status < 500) {
        // 客户端错误
        reject(new Error(`客户端错误: ${status}`));
      } else if (status >= 500) {
        // 服务端错误
        reject(new Error(`服务器错误: ${status}`));
      } else {
        // 其他状态码
        reject(new Error(`未知状态码: ${status}`));
      }
    } catch (error) {
      reject(error);
    }
  });
}

export default {
  post(url: any, params?: any) {
    return axios({
      method: "post",
      url,
      data: params
    }).then(response => {
      return checkStatus(response);
    });
  },
  get(url: any, params?: any) {
    params = qs.stringify(params);
    return axios({
      method: "get",
      url,
      params
    }).then(response => {
      return checkStatus(response);
    });
  }
};

 

 

 

vite.config.ts

export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://xxxxxxxxx/api', // 目标服务器地址
        changeOrigin: true, // 是否改变源地址
        rewrite: (path) => path.replace(/^\/api/, ''), // 重写路径
        // 可以配置更多选项,如 logLevel, timeout 等
      },
    },
  },
})

 

posted @ 2024-09-27 13:51  龙卷风吹毁停车场  阅读(527)  评论(0)    收藏  举报