axios interceptor in Vue

Intercept in axios

1.1 Introduction:

        Interceptors include request interceptors and corresponding interceptors, which can be intercepted before the request is sent or after the response. There is an interceptors attribute on the axios object, which has two attributes, request and response. The axios.interceptors.request and axios.interceptors.response objects provide the use method to classify and set request interceptors and response interceptors.

        The use() method supports two parameters, the first parameter is a resolve function similar to Promise, and the second parameter is a reject function similar to Promise. We can execute synchronous or asynchronous coding logic in the resolve or reject function.

       According to the official website, its usage is as follows:

//2.1 请求拦截器
axios.interceptors.request.use(
  function (config) {
    //在请求之前做些什么
    return config
  },
  function (error) {
    //对请求错误做些什么
    return Promise.reject(error)
  }
)

//2.2 响应拦截器
axios.interceptors.response.use(
  function (response) {
    //对响应数据做点什么
    return response
  },
  function (error) {
    //对响应错误做点什么
    return Promise.reject(error)
  }
)

1.2 Application scenarios

        For example, if you send requests in the project, you need to carry the token value, then we can cleverly use the request interception technology of axios, so that we only need to intercept here, judge whether to log in or not, that is, whether the token value exists, and release the request if it exists. If it does not exist, jump to the corresponding page (usually the login page) according to the project requirements to obtain the token value and then log in. Examples are as follows:

1. Create an axios.js file in the api directory of the src directory

import axios from 'axios'
import store from '@/store/index' //引入store
import router from '@/router' //引入router

//第一步创建实例
//全局axios默认值
//1.可以使用axios.defaulys的方式  2.可以使用axios.create()的方式,以下使用方式2
//方式1
// axios.defaults.baseURL = "http://127.0.0.1:8888/api/private/v1/"
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//方式2
let instance = axios.create({
  headers: {
    'content-type': 'application/x-www-form-urlencoded'
  }
})

//第二步 设置拦截器
//2.1 请求拦截器
instance.interceptors.request.use(
  function (config) {
    let access_token = sessionStorage.getItem('access_token');
    //如果不存在字段,则跳转到登录页面
    if (!access_token) {
      router.push({
        path: '/login',
        query: {
          redirect: router.currentRoute.fullPath
        }
      })
      //终止这个请求
      return Promise.reject();
    } else {
      //token存在,则让每个请求头都加上这个token,后台会判断我这个token是否过期
      config.headers.Authorization = access_token; //token放在请求头那个字段根据后端而定
    }
    //到了这一步就是循序发送请求
    return config;
  },
  function (error) {
    //对请求错误做些什么
    // err为错误对象,但是在我的项目中,除非网络问题才会出现
    Message.error({
      message: '请求超时!'
    })
    return Promise.reject(error);
  })

//2.2 响应拦截器
// http response 拦截器
instance.interceptors.response.use(
  response => {
    // 如果返回的状态码为200,说明接口请求成功,可以正常拿到数据
    // 否则的话抛出错误
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  // 服务器状态码不是2开头的的情况
  // 这里可以跟你们的后台开发人员协商好统一的错误状态码
  // 然后根据返回的状态码进行一些操作,例如登录过期提示,错误提示等等
  // 下面列举几个常见的操作,其他需求可自行扩展
  error => {
    if (error.response.status) {
      switch (error.response.status) {
        // 401: 未登录
        // 未登录则跳转登录页面,并携带当前页面的路径
        // 在登录成功后返回当前页面,这一步需要在登录页操作。
        case 401:
          vant.Toast.fail("身份验证失败,请关闭重新进入。");
          break;

        // 403 token过期
        // 登录过期对用户进行提示
        // 清除本地token和清空vuex中token对象
        // 跳转登录页面
        case 403:
          vant.Toast.fail("登录过期,请关闭重新进入。");
          // 清除token
          break;

        // 404请求不存在
        case 404:
          vant.Toast.fail("您访问的网页不存在。");
          break;
        // 其他错误,直接抛出错误提示
        default:
          vant.Toast.fail(error.response.data.message);
      }
      return Promise.reject(error.response);
    }
  }
);
//最后将实例导出来
export default instance

2. Import and mount on Vue in main.js

import instance from "./axios-init";//导入
//把axios 作为Vue的原型属性
window.axios = axiosInit();
Vue.prototype.$http = window.axios;//挂载

3. Use in the page

this.$http.post(url, params).then(res=>{}).catch(error=>{});

Guess you like

Origin blog.csdn.net/weixin_46872121/article/details/122005858