Vue interceptor principle and detailed use

Interceptor principle and function

  • First, the interceptor is in the src/utils/request.js file, and the interceptor is divided into a request interceptor and a response interceptor.

  • Every request in the page will go through request interception and response interception, so it is generally operated in this file.

  • This file generally introduces axios, vuex, Message, router and related methods, base address + interceptor.

  • Request interceptor: Token active processing adds a request header token to each request and throws an exception to the request.

  • Response Interceptor: Simplified Axios adds a layer of data Token by default to passively handle request exceptions.


Minimal version

// 导入axios
import axios from 'axios'

// 基地址
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // 5秒超时
  timeout: 10000
})

// 请求拦截
request.interceptors.request.use(
  config => {
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截
request.interceptors.response.use(
  res => {
    return res
  },
  // 响应错误的代码写这里
  error => {
    return Promise.reject(error)
  }
)

// 暴露副本
export default service

The following is used in actual development

Notice:

When we use axios, he will add a layer of data to us by default. In this way, when we fetch data, we will increase the invalid code, so we can judge when the data responds, and artificially remove a layer for others, as follows to judge return data, so that we can directly res.data. variable

Another one is token processing, which includes active processing: save a time when logging in, judge this time, call the logout method when it exceeds, prompt information, and return to the login page. Passive processing: Judging when there is an exception, if it is the token expiration status code specified with the backend (such as 401), call the logout method, prompt the message, and return to the login page.

The base address is best not to write the variable name by heart, so that we can quickly change the address by changing the environment file.

// 导入axios
import axios from 'axios'
// 导入提示信息
import { Message } from 'element-ui'
// 导入vuex
import store from '@/store'
// 导入路由
import router from '@/router'
// 导入获取时间和token的工具函数
import { getToken, getTokenTime } from '@/utils/auth'

// 基地址
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // 5秒超时
  timeout: 10000
})
// 请求拦截
// 添加一个service的请求拦截器
service.interceptors.request.use(
  async config => {
    // config就是本次发请求的信息
    // 判断有没有token
    if (store.state.user.token) {
      // token失效的主动处理
      // 获取一下记录token的时间
      let start = getTokenTime()
      // 获取一下当前时间
      let now = Date.now()

      // 算出时间差
      let hour = (now - start) / 1000 / 3600

      // 判断是否超过1小时
       if (hour >= 1) {
         // 代表token过期
         await store.dispatch('user/logout')
         Message.error('token已过期,请重新登录')
         router.push('/login')
      // return代表不往下执行,所以这个请求不会发送
         return
       }
       config.headers.Authorization = 'Bearer ' + getToken()
      config.headers['Bearer'] = getToken()
      // config.headers.tenantid =  getTenantId ()
    }
    // 发送请求
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 响应拦截
service.interceptors.response.use(
  res => {
    // axios默认加了一层data
    // 这个res包括这个请求响应回来的所有信息
    // 所有的接口请求都会回到这里
    // 获取到本次请求得到的数据
    const data = res.data
    // 会帮所有的请求打印
    // console.log(data);
    // 判断本次请求是否成功
    if (data.code === 200 || data.code == 0) {
      // 如果响应成功,则正常给他返回数据
      return data
    } else {
      // 证明失败,我们需要让外面的catch被调用
      // 要让catch被调用,就要手动抛出一个错误,并把服务器返回的消息抛回去
      Message.warning(data.message || data.msg)
      return Promise.reject(data.message)
    }
  },
  async error => {
    // token失效的被动处理
    console.log(error)
    if (error.response.data.code === 401) {
      await store.dispatch('user/logout')
      Message.warning('登录状态过期,请重新登录!')
      router.push('/login')
    } else {
      return Promise.reject(error)
    }
  }
  // error => {
  //   return Promise.reject(error)
  // }
)
// 暴露副本
export default service

browser access

img


Summarize:

After this process, I believe you have a preliminary deep impression on the principle and detailed use of the Vue interceptor, but the situation we encounter in actual development must be different, so we need to understand its principle, ever-changing Stay true to its roots. Come on, hit the workers!

Please point out any deficiencies, thank you -- Fengguowuhen

Guess you like

Origin blog.csdn.net/weixin_53579656/article/details/128086066
Recommended