编程知识 cdmana.com

The use of Axios interceptor

Simple packaging axios, Use the request interceptor to set up token; Use the response interceptor to intercept the error code returned from the background , And judge token Is it overdue ;

main.js Introduce encapsulated axios, And add it to the prototype ;

//  introduce axios
import http from "@utils/http.js";
Vue.prototype.axios = http;

After the encapsulation axios( Relatively simple , I hope it helps you )

/**
 *  encapsulation axios
 *  Create a qs Escaped axios, Add to the prototype , Create a normal axios, For other requests 
 *  Request to intercept , Set the head token
 *  The response to intercept , Block the error message returned by the background 
 *   Judge token Is it overdue , Jump to login page after expiration 
 */

//   Introduce modules 
import { Toast } from "vant";
import axios from "axios";
import router from "@/router.js";
import qs from "qs";

//  Global request address 
const baseUrl = "http://192.168.3.6:8000";

//  establish qs Conversion parameter format , And add to http On the prototype ( Because of the special situation in the backstage , This request is only once , namely qsAxios Negligible )
let qsAxios = axios.create({
  baseURL: baseUrl,
  timeout: 3000,
  //  You can set a  `baseURL`  Convenient for  axios  Method transfer relative of instance  URL
  transformRequest: [
    function(data) {
      // `transformRequest`  Allow before sending to server , Modify request data 
      //  Can only be used in  'PUT', 'POST'  and  'PATCH'  These request methods 
      return qs.stringify(data);
    },
  ],
});

//  Create common axios
let http = axios.create({
  baseURL: baseUrl,
  timeout: 3000,
});

http.qsAxios = qsAxios;

// axios Request to intercept 
http.interceptors.request.use(
  (response) => {
    var token = localStorage.getItem("token");
    //  Judge whether it exists token, If it exists , Then each http header All plus token
    if (token) {
      response.headers["token"] = token;
    }
    return response;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// axios The response to intercept 
http.interceptors.response.use(
  (response) => {
    console.log(response);
    return response;
  },
  (error) => {
    if (error.response) {
      // Make an appointment with the backstage , Set different status codes , If appear error.response appear undefined, Check whether the back end is intercepted by middleware in advance 
      switch (error.response.status) {
        case 400:
          Toast(error.response.data.msg);
          break;
        case 401:
          Toast(" Login information has expired , Please login again !");
          router.replace({ path: "/login", name: "login" });
          break;
        case 404:
          Toast(" Request error , Please refresh and try again !");
          break;
        case 422:
          Toast(" Parameter error , Please try again later !");
          break;
        case 500:
          Toast(" Request error , Please refresh and try again !");
          break;
      }
    }
    return Promise.reject(error);
  }
);

export default http;

Use

  1. adopt qs escape
this.axios.qsAxios.post("/test").then((res)=>{})
  1. Ordinary axios
this.axios.post("/test").then((res)=>{})

版权声明
本文为[Brief]所创,转载请带上原文链接,感谢

Scroll to Top