axios使用拦截器添加token,限制快速点击,超时重新发送请求

  1. 此处使用了vux框架,可根据需要修改
  2. 自行填写域名地址
  3. token添加的方式及位置,根据需求添加。(此处token保存在localStorage中)
  4. token过期的条件限制及 token过期后的操作,根据需要修改。
  5. 请求超时时,重新发送请求。
  6. 最后为的get和post请求例子
import axios from 'axios';
import Vue from 'vue';
import store from '../store/'
import router from "../router"
import utilCon from '../assets/js/utilCon.js'
import {
    ToastPlugin,
    LoadingPlugin
} from 'vux'
Vue.use(ToastPlugin)
Vue.use(LoadingPlugin)

var qs = require('qs');

// 限制快速点击
var requesting = []
var limitTime = 2000 //請求間隔時間
var requestingId = ''

var time = null;

Vue.prototype.$dataToken = utilCon.dataToken;

if(process.env.NODE_ENV === 'development') {//开发环境
    axios.defaults.baseURL = '地址'; //请求域名地址
} else {//正式环境
    axios.defaults.baseURL = ipconfig;
}
axios.defaults.timeout = 5000  //請求過期時間
Vue.prototype.$axios = axios.defaults.baseURL


// 显示loading
let loadingFn = (config)=>{
    if(config.data && (config.data.toString().indexOf('noLoading') >= 0)) {} else {//对不需要loading的部分做出筛选
        clearTimeout(time)
        time = (setTimeout(() => {
            Vue.$vux.loading.show({
                text: ''
            })
        }, 1000))
    }
}

// 添加请求拦截器
axios.interceptors.request.use(function(config) {
    // 添加token
    let token = localStorage.getItem("Token");
    if (token) {
        config.headers.common['Authorization'] = 'Bearer ' + token
    }

    // 限制快速点击
    var requestingId = JSON.stringify(config.data)
    if(config.method === 'post' && requestingId) {
        let nowTime = new Date().getTime()
        requesting = requesting.filter(item => {
            return item.startTime + limitTime > nowTime //筛选请求时间间隔
        })
        let sessionUrl = requesting.filter(item => {
            return item.requestingId === requestingId;//参数对比
        })

        if(sessionUrl.length > 0) {
            // 请求重复 中断请求(目前还没找到更好的方法,如果return false   会导致页面报错,虽然不影响页面效果及功能
           //此处通过修改请求(请求一个没多大作用并且返回快的地址),来达到只请求一次的效果,也可对其进行筛选
            config.url = '/api/getdatatoken';
            config.method = 'post';
            return config
        } else {
            let item = {
                requestingId: requestingId,
                startTime: nowTime
            }
            requesting.push(item);
            
            loadingFn(config);
            return config
        }
    } else {
        loadingFn(config);
        return config;

    }
}, function(error) {
    // 对请求错误做些什么
    Vue.$vux.loading.hide()
    return Promise.reject(error)
});

// 添加响应拦截器
axios.interceptors.response.use(function(response) {
    // 对响应数据做点什么
    clearTimeout(time);
    time = null;
    Vue.$vux.loading.hide();
   //to do something...
    } else if (response.data.hasOwnProperty('rst') && response.data.rst != true && response.data.msg) { //请求失败
       //to do something...
    }
    return response;
}, function(error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});


//axios请求超时,设置重新请求
axios.defaults.retry = 4
axios.defaults.retryDelay = 5000;
//不可發送多次請求的接口
let unrepeatStr = '/api/reg,/api/submitorder';

axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
    var config = err.config;
    // If config does not exist or the retry option is not set, reject
    if (!config || !config.retry) return Promise.reject(err);

    //判斷是否不發送多次請求
    let configUrl = config.url;
    let newUrl = configUrl.substring(configUrl.indexOf("/api"));;
    if(unrepeatStr.indexOf(newUrl)>=0){
        return Promise.reject(err)
    }
    // Set the variable for keeping track of the retry count
    config.__retryCount = config.__retryCount || 0;

    // Check if we've maxed out the total number of retries
    if (config.__retryCount >= config.retry) {
        // Reject with the error
        clearTimeout(time);
        time = null;
        Vue.$vux.loading.hide();
        Vue.$vux.toast.text('连接超时,请稍后重试...', 'middle')
        return Promise.reject(err);
    }

    // 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);
    });
});


//---------------get请求---------------------
export const getinfo= () => {
    return axios.get('/api/getinfo');
}

//---------------post请求---------------------
//获取是否重复请求得token
export const getdatatoken = (pms) => {
    const params = qs.stringify(pms)
    return axios.post('/api/getdatatoken',params)
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容