美文网首页
axios请求封装文件

axios请求封装文件

作者: 陶菇凉 | 来源:发表于2021-01-14 16:51 被阅读0次

axios封装了的公共文件 utils/request.js

import axios from 'axios';
import store from '@/store';
/* 封装axios请求 */
const instance = axios.create({
  timeout: 60000,
  /* baseURL:  "/" "/api/"  在此处写baseurl当数据请求失败再次请求数据的时候会导致baseURL叠加 */
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  } /* 设置post请求的数据格式 */,
  withCredentials: true /* 设置请求头携带cookie */,
  retry: 3 /* 设置请求失败之后重新请求次数 */,
  retryInterval: 5000 /* 设置请求失败之后再次发起请求的间隔 */
});
instance.interceptors.request.use(
  config => {
    if (store.getters.token) {
      // config.headers['www-authenticate'] = getToken();
      config.headers['Authenticate'] = window.localStorage.getItem('token');
    }
    return config;
  }
);
/* 设置请求失败之后重新发起请求*/
instance.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    return Promise.reject(error);
  },
  function axiosRetryInterceptor(err) {
    var config = err.config;
    if (!config || !config.retry) {
      return Promise.reject(err);
    }
    /* If config does not exist or the retry option is not set, reject */
    config.__retryCount =
      config.__retryCount ||
      0; /* Set the variable for keeping track of the retry count */
    // Check if we've maxed out the total number of retries
    if (config.__retryCount >= config.retry) {
      return Promise.reject(err); /* Reject with the error */
    }

    // Increase the retry count
    config.__retryCount += 1;

    // Create new promise to handle exponential backoff
    var backoff = new Promise(function(resolve) {
      setTimeout(function() {
        resolve();
      }, config.retryDelay || 1);
    });

    // Return the promise in which recalls axios to retry the request
    return backoff.then(function() {
      return axios(config);
    });
  }
);

const baseURL = '/api'; 
export function get(url, config) {
  return instance.get(baseURL + url, config);
}

export function post(url, data, config) {
  return instance.post(baseURL + url, data, config);
}

export function putAction(url, data, config) {
  return instance.put(baseURL + url, data, config);
}

export function deleteAction(url, data, config) {
  return instance.delete(baseURL + url, data, config);
}

相关文章

网友评论

      本文标题:axios请求封装文件

      本文链接:https://www.haomeiwen.com/subject/ecbvaktx.html