vue3 ts 封装Axios

npm i axios
import axios from 'axios';
import { AxiosInstance, AxiosRequestConfig } from 'axios';
// 将axios封装到类中
class Http{
  instance: AxiosInstance; // axios的实例将被保存到这里
  constructor(config: AxiosRequestConfig) {
    // 构造器里的config包括baseURL,timeout等
    this.instance = axios.create(config); //创建axios实例
    this.instance.interceptors.request.use(
      //实例中的请求拦截器
      (config) => {
        //请求成功的拦截
        return config;
      },
      (error) => {
        //请求失败的拦截
        return Promise.reject(error);
      }
    );
    this.instance.interceptors.response.use(
      //实例中的响应拦截器
      (response) => {
        //响应成功的拦截
        return response;
      },
      (error) => {
        //响应失败的拦截
        return Promise.reject(error);
      }
    );
  }
  request<T>(config: AxiosRequestConfig): Promise<T> {
    //再次封装request方法
    return new Promise((resolve, reject) => {
      this.instance
        .request<any, T>(config)
        .then((res) => {
          resolve(res); //将结果返回出去
        })
        .catch((err) => {
          reject(err);
          return err;
        });
    });
  }
  get<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' });
  }
  post<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' });
  }
  delete<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE' });
  }
  patch<T>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'PATCH' });
  }
}
export default Http;

import Http from './http';  // 就是上面的实例

const http = new Http({
  baseURL: 'http://10.138.103.7:3005',
  timeout: 3000
});
export default http;

使用。post的参数都会被解构出来

import http from '../../utils/request';
  http.post({
      url: '/cloudctl/getAllMapInfos'
    }, 参数) 
    .then((res) => {
      console.log('axios接口获取的数据', res);
    });

你可能感兴趣的:(vue,http,javascript)