Vue中的axios请求封装

2018-12-23  本文已影响0人  二营长家的张大炮
镇楼.jpg

axios.interceptors.request.use() // 开始进行拦截请求。
axios.interceptors.response.use()//拦截请求响应数据。

在发送axios请求时,如果每个组件都需要各自发送的话,那么代码太过冗余。
所以可以将请求方法进行封装。

创建ajax.js用于处理各种请求方式:
最近进行了优化:新增一个单独的关于文件上传的请求函数

import axios, {
  AxiosRequestConfig,
  AxiosResponse,
  AxiosError
} from 'axios'

// timeout 10min
const Global_Delay = 10 * 60 * 1000;

const BASE_URL = 'http://127.0.0.1:9898/blogManage';
// 定义一个空的数组,用于存放请求中的参数

// 创建axios实例
const axiosInstance = () => {
  const instance = axios.create({
    baseURL: BASE_URL,
    timeout: Global_Delay,
  });
  return instance;
};


// 请求实例
const publicReq = async (params: { [key: string]: any }) => {
  const {
    url,
    method,
    param
  } = params;
  const instance = axiosInstance();
  return await instance({
    url,
    method,
    // 在请求头里面添加token 如果没有则为空字符串
    headers: {
      'token': localStorage.getItem('token') === null ? '' : localStorage.getItem('token')
    },
    [method === 'post' ? 'data' : 'params']: param || {},
    transformRequest: [function (data) {
      let ret = ''
      let index = 0;
      for (let key in data) {
        if (data[key] === null) {
          ret += `${index === 0 ? '' : '&'}key=&`
        } else {
          ret += `${index === 0 ? '' : '&'}${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`
        }
        index += 1;
      }
      return ret
    }]
  }).then((res: AxiosResponse) => {
    if (res) {
      if (res.data.code === 403) {
        window.location.href = "/signin";
        localStorage.removeItem("name");
        localStorage.removeItem("id");
        localStorage.removeItem("avatar_url");
        localStorage.removeItem("token")
        throw new Error(res.statusText);
      }
      if (res.data.code !== 200) {
        throw new Error(res.data.data)
      } else {
        return res.data;
      }
    }
  });
};

// 请求超时函数
const timeoutfn = (delay: number, url: string) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('请求超时');
    }, delay);
  });
};

// 单个请求 存在请求超时
export async function req(params: { [key: string]: any }, delay = Global_Delay) {
  try {
    const response: any = await Promise.race([
      timeoutfn(delay, params.url),
      publicReq(params),
    ]);
    if (response.data.code === 401) {
      localStorage.removeItem("token");
      location.href = '/';
    }
    return response;
  } catch (error) {
    throw new Error(error);
  }
}

// GET request
export async function getRequest(url: string, param: { [key: string]: any }) {
  try {
    const response = await req({
      url,
      method: 'get',
      param,
    });
    return response;
  } catch (err) {
    console.log(err);
  }
}

// POST request
export async function postRequest(url: string, param: { [key: string]: any }) {
  try {
    const response = await req({
      url,
      method: 'post',
      param,
    });
    return response;
  } catch (err) {
    console.log(err);
  }
}


如果模块过多可以分文件存储然后在index.js文件下引入向外暴露

import AdminModule from "./admin"
import ArticleModule from "./article"
import BannerModule from "./banner"
import DictionaryModule from "./dictionary"
import UploaderModule from "./uploader"

export default {
  AdminModule,
  ArticleModule,
  BannerModule,
  DictionaryModule,
  UploaderModule
}
上一篇下一篇

猜你喜欢

热点阅读