欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue中axios封装http请求

程序员文章站 2022-03-04 23:45:11
...
import Vue from 'vue'

import axios from 'axios'

import qs from 'qs'


//axios的一些公共配置和拦截器,比如发送请求显示loading,请求回来loading消失之类的


let loadTimeoutId;

//请求拦截配置;配饰author;携带token

axios.interceptors.request.use((config) => {
  loadTimeoutId = setTimeout(() => {
    new Vue({}).$vux.loading.show({
      text: 'Loading'
    });
  }, 500);
  setTimeout(() => {
    new Vue({}).$vux.loading.hide();
  }, 600);
  config.auth = {
    username: 'lin',
    password: 'lin'
  };
  console.log(config);
  return config
}, (error) => {
  clearTimeout(loadTimeoutId);
  //这里给'请求失败提示信息'
  return Promise.reject(error)
});

//响应拦截配置;根据后端返回的code码 做不同的处理

axios.interceptors.response.use((res) => {
  clearTimeout(loadTimeoutId);
  if (res.status == 200) {
    return res;
  }
}, (error) => {
  //这里给响应失败提示信息
  return Promise.reject(error)
});


let ajax = {
  get: (url, params, successCallback, errorCallback) => {
    axiosRequestParams(url, 'get', params, 10000, successCallback, errorCallback)
  },
  post: (url, params, successCallback, errorCallback) => {
    axiosRequestParams(url, 'post', params, 15000, successCallback, errorCallback);
  },
  //上传文件
  upload: (url, params, successCallback, errorCallback, formData) => {
    axiosRequestParams(url, 'post', params, 0, successCallback, errorCallback, formData)
  }
};

function axiosRequestParams(url, method, paramsOrData, timeout, successCallback, errorCallback, formData) {
  let params = {};
  let data = {};
  paramsOrData = paramsOrData || {};
  paramsOrData.accessToken = window.sessionStorage.getItem('myAccessToken');
  paramsOrData.accessUserId = window.sessionStorage.getItem('myUserId');

  if (method === 'get' || method === 'delete' || method === 'head') {
    params = paramsOrData;
  } else {
    //qs.parse()将URL解析成对象的形式
    //qs.stringify()将对象 序列化成URL的形式,以&进行拼接
    // axios post 传递是 在data中的;
    data = qs.stringify(paramsOrData)
  }

  //有formData 走这个
  if (formData != null) {
    for (let attr in paramsOrData) {
      formData.append(attr, paramsOrData[attr])
    }
  }

  axiosRequest({
    method: method,
    url: url,
    params: params,
    data: formData ? formData : data,
    timeout: 10000
  }, successCallback, errorCallback)
}

function axiosRequest(conf, successCallback, errorCallback) {
  axios({
    method: conf.method || 'get',
    url: conf.url,
    params: conf.params || {},
    data: conf.data,
    timeout: conf.timeout || 10000
  }).then((res) => {
    successCallback(res.data);
  }).catch((res) => {
    if (errorCallback) {
      errorCallback(res.data);
    }
  })
}

Vue.prototype.$ajax = ajax

 

相关标签: axios