项目中往往会遇到,当长时间不发送请求,或者不操作之后,我们再发送axios请求,返回的数据就会存在一个超时的标志。我们在前端接收到这个超时数据时就需要进行做出判断,大多数的操作是跳转到登录页面,让用户重新登录。
前一段时间,做项目的时候,为了解决超时跳转这个问题,我把所有请求数据都加了if else去判断,进行超时天转到登录页面,简直了,所有接口。直到今天,实在不想加了,然后就去找一些解决方案,然后:
就是今天要介绍的

axios拦截

首先了解一下axios拦截是什么

请求拦截器

// http request 拦截器
instance.interceptors.request.use(
  config => {
    const token = sessionStorage.getItem('token')
    if (token ) { // 判断是否存在token,如果存在的话,则每个http header都加上token
      config.headers.authorization = token  //请求头加上token
    }
    return config
  },
  err => {
    return Promise.reject(err)
  })

响应拦截器

// http response 拦截器
instance.interceptors.response.use(
  response => {
    //拦截响应,做统一处理 
    if (response.data.code) {
      switch (response.data.code) {
        case 1002:
          store.state.isLogin = false
          router.replace({
            path: 'login',
            query: {
              redirect: router.currentRoute.fullPath
            }
          })
      }
    }
    return response
  },
  //接口错误状态处理,也就是说无响应时的处理
  error => {
    return Promise.reject(error.response.status) // 返回接口返回的错误信息
  })

解决请求任意接口之前进行统一拦截判断,看是否返回500或404等错误并在页面给出错误提示。

在vue项目中改如何使用呢?
因为是全局拦截,首先我找到了main.js文件。
在main.js中是这样写的

import axios from 'axios'
import router from './router'//
import {message} from './lib/js/resetMessage'//

// 全局请求拦截器
axios.interceptors.response.use(function (response) {
  // console.log(response.data.TimeOutFlag)
  if (response.data.TimeOutFlag) {
    // console.log('超时了')
    router.push('/login')//跳转到登录页面
    message({
      showClose: true,
      message: response.data.Msg,
      type: response.data.Check ? 'success' : 'error'
    })
  }
  return response
})

这样在项目中无论请求哪一个接口,都会对请求响应进行监控,判读那是否有超时的标志。
欧克,每天学一招,今天就分享这些啦,欢迎大家参考交流,不足之处请指出

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐