VUE

Vue实现禁止反复发送请求

2022-10-09  本文已影响0人  空格x

1.最基础的请求基础代码

import axios from 'axios'
import { getItem, removeItem } from '@/utils/token'
import { Message } from 'element-ui'
import router from '@/router'
const request = axios.create({
  baseURL: "/api",
})
// 请求拦截器
request.interceptors.request.use(function (config) {
  config.headers.Authorization = `Bearer ${getItem("token")}`
  return config;
})
// 响应拦截器
request.interceptors.response.use(function (config) {
  const { status, message } = config.data
  if (status == '500') {
    Message.error('登录已过期,请重新登录')
    removeItem('token')
    router.push('/login')
  } else if (status !== '200' && status !== '500') {
    Message.error(message)
  }
  return config
}, error => {
  console.log(error);
  return Message.error(error)
})
export default request

2. 获取这次请求的请求信息,并做重复拦截

let requestList = []
// 请求拦截器
// 同时记录请求地址与请求方式防止拦截错误 
request.interceptors.request.use(function (config) {
  if (requestList.findIndex(x => x.config === `${config.url}&${config.method}`) === -1) {
    requestList .push({ config: `${config.url}&${config.method}` })
  } else {
    return
  }
  config.headers.Authorization = `Bearer ${getItem("token")}`
  return config;
})

3. 请求结束后清除此接口信息

// 响应拦截器
request.interceptors.response.use(function (config) {
  requestList = requestList.filter((x,index)=>x.config !== `${config.config.url}&${config.config.method}`)
  const { status, message } = config.data
  if (status == '500') {
    Message.error('登录已过期,请重新登录')
    removeItem('token')
    router.push('/login')
  } else if (status !== '200' && status !== '500') {
    Message.error(message)
  }
  return config
}, error => {
  console.log(error);
  return Message.error(error)
})
TypeError: Cannot read properties of undefined (reading 'cancelToken')

4. 完整代码

import axios from 'axios'
import { getItem, removeItem } from '@/utils/token'
import { Message } from 'element-ui'
import router from '@/router'
const request = axios.create({
  baseURL: "/api",
let requestList = []
// 请求拦截器
// 同时记录请求地址与请求方式防止拦截错误 
request.interceptors.request.use(function (config) {
  if (requestList.findIndex(x => x.config === `${config.url}&${config.method}`) === -1) {
    requestList .push({ config: `${config.url}&${config.method}` })
  } else {
    return
  }
  config.headers.Authorization = `Bearer ${getItem("token")}`
  return config;
})
// 响应拦截器
request.interceptors.response.use(function (config) {
  requestList = requestList.filter((x,index)=>x.config !== `${config.config.url}&${config.config.method}`)
  const { status, message } = config.data
  if (status == '500') {
    Message.error('登录已过期,请重新登录')
    removeItem('token')
    router.push('/login')
  } else if (status !== '200' && status !== '500') {
    Message.error(message)
  }
  return config
}, error => {
  console.log(error);
  return Message.error(error)
})
export default request

上一篇下一篇

猜你喜欢

热点阅读