Recently, while building a project, I came up with the idea of encapsulating the request and wondered how best to encapsulate it. Although it may be a small thing for you, it is also a small challenge for me. I assumed that some of the requested basic configuration and specific interfaces would be in two files, so I created two new files axios.js and api.js

axios.js

Axios.js is basically the basic configuration for AXIos: baseURL request interceptor response interceptor and so on

import axios from 'axios';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import router from '.. /router';
Copy the code

First, axios is introduced in the current JS, element is introduced so that its components can be used in the current JS, and the purpose is to prompt the various return values directly in the response interceptor. The Router was introduced to jump to a page based on a specific return value in the response interceptor, such as a login page without permission

if (process.env.NODE_ENV === 'development') {
  axios.defaults.baseURL = 'api';
} else if (process.env.NODE_ENV === 'production') {
  axios.defaults.baseURL = 'https://xxxxxxxxxx/index/';
}
Copy the code

For baseURL processing, I distinguish between development and production environments

// The request interceptor distinguishes a normal request from the request header when sending formData
axios.interceptors.request.use((config) = > {
  config.headers['Content-Type'] = 'application/json';
  if (config.method === 'post') {
    // The request header for FormData
    if (Object.prototype.toString.call(config.data) === '[object FormData]') {
      // Request interceptor processing
      config.headers['Content-Type'] = 'multipart/form-data';
    } else if (Object.prototype.toString.call(config.data) === '[object String]') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'; }}else {
    config.headers['Content-Type'] = 'application/json';
  }
  return config;
});

// Response interceptor
axios.interceptors.response.use(
  (config) = > {
    let value = config.data;
    if (config.status && config.status === 200) {
      if (typeof value === 'string') {
        if (value === 'timeout') {
          ElementUI.MessageBox.confirm('Too long time no operation or operation does not have permission, please enter the login page to log in again? '.'tip', {
            confirmButtonText: 'sure'.type: 'warning'
          }).then(() = > {
            router.push({ name: 'login' });
          });
        }else{ ElementUI.Message.info(value); }}}return config;
  },
  (err) = > {
    let value = err.response.statusText;
    switch (err.response.status) {
      case 400:
        ElementUI.Message.error('Syntax is wrong, server cannot understand this request')
        break;
      case 401:
      case 403:
      case 404:
      case 405:
        ElementUI.Message.warning(value);
        break;
      default:
        ElementUI.Message.error('Error during operation, this operation is invalid! ' + value);
        break;
    }
    return err.response
  }
);
Copy the code

In the case of the response interceptor, I’m going to deal with the value returned by my own back end, because I didn’t do much with the back end so I’m just going to do a little bit of processing on the return, okay

Here is an encapsulation of GET and POST

export async function axiosGet(url, params = {}) {
  let res = await axios.get(url, { params: params });
  if(res.status === 200) {return res.data
  }else {
    throw res.statusText
  }
}

export async function axiosPost(url, params = {}) {
  let res = await axios.post(url, params);
  if(res.status === 200) {return res.data
  }else {
    throw res.statusText
  }
}
Copy the code

Use async and await to get the returned value directly for judgment. If the return is successful, the returned value will be output. If not, an error will be thrown and the encapsulated method will be exported

api.js

The entire api.js is where all the interfaces in the project are stored

import { axiosGet,axiosPost } from './axios'
Copy the code

Import axios.js to get the wrapped axiosGet and axiosPost

export default {
  getLogin:(params = {}) = > {
    return axiosPost('/login', params)
  },
  getUser:(params = {}) = > {
    return axiosGet('http://localhost:3000/user', params)
  }
}
Copy the code

I’m using two simple interfaces for examples here, and the processing is done in api.js

Use the configured interface

Now that our Axios is wrapped, it’s time to demonstrate how to use it

import DbauditServer from '@/server/api'
// Introduce api.js in the file to call the interface

let formData = new FormData
formData.append('password'.this.formLabelAlign.password)
let res1 = await DbauditServer.getLogin(formData) // Call it directly
let res2 = await DbauditServer.getUser()
Copy the code

We can also use a try catch to wrap interface calls, which can be handled with a specific error.