axios interceptor + default parameter configuration + custom header settings + unified error handling

Keywords: Front-end axios Attribute github

axios interceptor + default parameter configuration + custom header settings + unified error handling

This configuration file can fulfill simple project requirements, and the specific configuration depends on the project. It mainly includes:

  • axios interceptor
  • Default parameter configuration
  • Custom header settings
  • Unified error handling
  • Request encapsulation
  • api unified management

axios interceptor (request interceptor)

Object.assign if the attribute in the target object has the same key, the attribute will be overwritten by the attribute in the source object. The properties of the subsequent source object will similarly override the properties of the previous source object. - MDN

// axiosInterceptor.js
// Directory: src directory create utils directory to store http configuration files, axios files and interface unified management files
// Add request interceptor
axios.interceptors.request.use(
  config => {
    // Default parameter settings: values that all interfaces must pass (for example: userId)
    let defaultParams = {
      userId: store.state.userId;
    };
    // Custom header information (such as token)
    config.headers['B-Token'] = store.state.token;
    // The default value is combined with the parameters from the interface (Note: interface parameters and default values cannot be duplicate)
    config.data = Object.assign(defaultParams, config.data);
    return config;
  }, function (error) {
    // What to do about request errors
    return Promise.reject(error);
  });

axios interceptor (response interceptor)

// axiosInterceptor.js
// Add response interceptor
// Do some processing for the back-end return value
axios.interceptors.response.use(function (res) {
  // What to do with response data
  // All status codes come from the backend. Alas ~ all status codes are returned in res.data
  // The status code here can be modified according to the actual situation

  // Data normally returns 200
  if(res.data.code=='200'){
    return Promise.resolve(res);
  }else {
    // Return in case of abnormal data (for example, token expired, insufficient parameters)
    // See the errorCode file for details of judgeErrorCode
    judgeErrorCode(`code${res.data.code}`, res.data.msg)
    return Promise.reject(res);
  }
}, function (error) {
  // What to do about response errors
  judgeErrorCode(`code${500}`, 'unknown error');
  return Promise.reject(error);
});

Unified error handling

The most fundamental function of polymorphism is to eliminate these conditional branch statements by transforming them into object polymorphism

// message.js file
// The message prompt is encapsulated separately, and the message file is introduced
import { errorMess } from './message.js'

import store from '../store';
// Because I don't want to judge (lazy) in every code, I will put all the judgments out and judge in the interceptor (code may be the same, but the prompt information is different)
// Only the successful return data is written in the code
// Too many conditions do not consider condition judgment (may be added later)
// Modifying code is often more dangerous than increasing it

const judgeErrorCode = (code, message) => {
  // Determine whether errorCode[code] is a function
  if(errorCode[code] instanceof Function){
    // Call this function
    errorCode[code](message);
  }
};
const errorCode = {
  // Different operations need to be performed according to different status codes
  code201: function(message){
    errorMess(message);
    // console.log('update failed ');
  },
  code202: function(message){
    // console.log('insufficient parameters');
    errorMess(message);
  },
  code203: function(message){
    // console.log('input error ');
    errorMess(message);
  },
  code400: function(){
    // console.log('token cannot be empty ');
    // Clear the local user ID and log in again
    store.commit('TO_LOGIN');
  },
  code500: function(message){
    // Server error
    errorMess(message);
  },
}
export default judgeErrorCode;

http encapsulation

// There are many ways to encapsulate http requests, but they are the same
export const postRequest = (url,params,headers={'Content-Type': 'application/x-www-form-urlencoded'}) => {
  return axios({
    method: 'post',
    url,
    data: params,
    transformRequest: [function (data) {
      let req = '';
      for (const key in data) {
        req += encodeURIComponent(key) + '=' + encodeURIComponent(data[key]) + '&'
      }
      return req;
    }],
    headers,
  })
};

Unified interface management

The interface is put together for later management and maintenance

  import { postRequest, getRequest, filesRequest, jsonRequest } from '../utils/http'

  // User information interface (example)
  export const getUserInfoData = params => postRequest('/v1/getUserInfoData', params);

epilogue

If there is anything wrong with the cognition of Xiaobai in the front end, please inform us to modify it
Detailed configuration files can be found in github See

Posted by mie on Fri, 08 Nov 2019 12:21:09 -0800