axios 路由跳转取消请求

1.store:

(1)state:

const state = {
  axiosCancelTokens: [] // axios取消请求的token集合
}

(2)mutation-types:

export const AXIOS_PUSH_TOKEN = 'AXIOS_PUSH_TOKEN' // 添加新的axios请求
export const AXIOS_CLEAR_TOKEN = 'AXIOS_CLEAR_TOKEN' // 清楚axios请求

(3)mutations:

import * as types from './mutation-types'
import { constAxios } from '@/utils/constant'

export default {
  [types.AXIOS_PUSH_TOKEN]: (state, src) => {
    state.axiosCancelTokens.push(src.cancelToken)
  },
  [types.AXIOS_CLEAR_TOKEN]: ({axiosCancelTokens}) => {
    axiosCancelTokens.forEach(item => {
      item(constAxios.requestCancelDesc)
    })
    axiosCancelTokens = []
  }
}

2.router:

import store from '@/store'
import * as types from '@/store/mutation-types'

// 导航守卫
router.beforeEach((to, from, next) => {
  store.commit(types.AXIOS_CLEAR_TOKEN)// 取消请求
  next()
})

3.axios:

/**
 * @file request.js axios配置
 */

import axios from 'axios'
import { MessageBox, Indicator, Toast } from 'mint-ui'
import { getStore, loginOut } from '../utils/index'
import store from '@/store'
import * as types from '@/store/mutation-types'
import { constAxios } from '@/utils/constant'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? '' : process.env.BASE_API,
  timeout: constAxios.timeout // 请求超时时间
})

axios.defaults.headers.post['Content-Type'] = 'application/json-patch+json'
axios.defaults.retry = 3
axios.defaults.retryDelay = 1000

// 添加请求拦截器
service.interceptors.request.use((config) => {
  // 添加请求
  config.cancelToken = new axios.CancelToken((cancel) => {
    store.commit(types.AXIOS_PUSH_TOKEN, {
      cancelToken: cancel
    })
  })
  // ...
  return config
}, (error) => {
  return Promise.reject(error)
})

service.interceptors.response.use(response => {
  // 对响应数据做些事
  // 1.关闭加载提示框
  Indicator.close()
  // 2.判断接口访问成功与否
  var result = response.data
  if (response.status !== 200) {
    MessageBox('提示', '接口访问失败,失败状态:' + response.status)
    return Promise.reject(response.status)
  } else if (!result.success) {
    var msg = result.msg
    MessageBox('提示', msg)
    return Promise.reject(msg)
  } else {
    return result
  }
}, (error) => {
  // 请求错误时做些事
  // 关闭加载提示框
  Indicator.close()
  // 判断是否是因为路由跳转取消请求
  if (error.message !== constAxios.requestCancelDesc) {
    // 判断是否是请求超时
    var originalRequest = error.config
    if (error.code === 'ECONNABORTED' && error.message.includes('timeout') && !originalRequest._retry) {
      var config = error.config
      MessageBox.alert('网络好像不太给力,请稍后再试').then(action => {
        originalRequest._retry = true
        return service.request(config)
      })
    } else if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
      Toast({
        message: `请求超时!`,
        position: 'bottom'
      })
    } else if (error.response) {
      if (error.response.status === 401) {
        // MessageBox.alert('抱歉,您没有此操作权限!').then(action => {
        //   // loginOut()
        // })
      } else {
        MessageBox('提示', `接口访问失败:${error.message}(${error.response.status})`)
      }
    } else {
      MessageBox('提示', '接口访问失败,' + error.message)
    }
  }
  return Promise.reject(error)
})

export default service

4.constant:常量

/**
 * 常量集合
 */

/**
 * axios取消请求的描述
 */
export const AXIOS_REQUEST_CANCEL = '取消请求'

5.参考:

(1)axios npm:https://www.npmjs.com/package/axios
(2)路由跳转取消请求:https://blog.csdn.net/echo_Ae/article/details/89174777

你可能感兴趣的:(Vue)