The axios secondary encapsulation and interceptor in the vue2 project (the whole article is super detailed) is also suitable for novices.

Catalog

  1. The basic configuration first installs the axios globally.

  2. Create a file named request.js and place it under utils.(The request name can be modified according to your preference.)

  3. Package the code directly. The detailed notes are written in the code, which can be copied directly and then modified as required.

  4. Note: The status of the interceptor needs to be processed according to the data returned from the background.

  5. The above axios has been encapsulated, and a api document needs to be created.(Document clarity is not too hard to find)

VI. Get and post Requests in api/user.js Simple Package


1. The basic configuration first installs the axios globally.

npm install axios

 2. Create a file named request.js and place it under utils.(The request name can be modified according to your preference.)

  3. Package the code directly. The detailed notes are written in the code, which can be copied directly and then modified as required.

 import axios from 'axios';

// basic configuration
const instance = axios.create({
  baseURL: 'http://localhost:3000/', // Modify according to actual situationAPIaddress
  timeout: 5000 // Set timeout,Unit isms
});

// request interceptor
instance.interceptors.request.use(config => {
  config.headers['Authorization'] = localStorage.getItem('token'); // Set request header part,Here the example is usedlocalStoragestoredtokenas an identity
  return config;
}, error => {
  console.log(error);
  return Promise.reject(error);
});

// response interceptor
instance.interceptors.response.use(response => {
  const data = response.data;
  if (data && data.code !== 200) { // Determine whether there is an error based on the status code returned by the interface
      alert(`Error code {data.code}:{data.message}`); // Custom error message
      return Promise.reject(new Error(data.message));
  } else {
      return data;
  }
}, error => {
  console.log(error);
  return Promise.reject(error);
});

export default instance; 

4. Note: The status of the interceptor needs to be processed according to the data returned from the background.

//Response interception processing  response interceptor:Contains two functions(One is a function that returns successfully,One is a function that returns on failure)
instance.interceptors.response.use(res => {
    // We usually handle it here,Error status code after successful request For example the status code is500,404,403
    // res is all the corresponding information
    console.log(res)
    return res.data
}, err => {
  let { res } = err
  if (res) {
    switch (res.status) {
      case 401:
        (Prompt based on status,The following states are allO)
        break
      case 403:
        break
      case 404:
        break
      case 500:
        break
    }
  } else {
    if (!window.navigator.onLine) {
      //Disconnection processing:Jump to disconnection page
      return
    }
  }
  // An error occurred in the server response
  return Promise.reject(err)
}) 

5. The above axios has been encapsulated, and a api document needs to be created.(Document clarity is not too hard to find)

VI. Get and post Requests in api/user.js Simple Package

//interface
//introduceaxios 
import request from '../utils/request'// This is where we are introducedaxiosuseaxiosTo make asynchronous interface requests

//For example, the interface is a registration interface
export function register(){
    return request({
        url:'/user/register',
        method:'post',
        data,  // generallypostask,we are used to using dataattributes to pass parameters

    })
}

export function login(){
    return request({
        url:'/user/login',
        method:'get',
        params,   //generallygetask,we are used to usingparamsattributes to pass parameters

    })
}


//The above is a case

      However, our url: ‘/user/register’ is such an address. Actually, we have written the prefix of the interface when encapsulating the axios. Therefore, we directly request/the interface parameters when introducing the address.

This document is transferred from https://blog.csdn.net/warmmmm_d/article/details/139805132,If there is any infringement,Please contact to delete。