1. Axios encapsulation

In Vue or React projects, we usually use AXIos, an HTTP library based on Promise, to fetch data in the background. It also runs in browsers and Node.js. It also has great features such as request and response interception, request cancellation, JSON conversion, client defense against XSRF, etc. If you’re not familiar with Axios, you can check out the Axios documentation. If you need to improve the place, please leave a comment below, if it is helpful to you, please give me a thumbs-up thank you.

The installation

NPM install

  npm install axios; 
Copy the code

Bower installation

  bower  install axios; 
Copy the code

Import using CDN (here we use jsDelivr)

  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Copy the code

Introducing axios library

Create a new utils folder in the SRC path of our project and create a JS file named HTTP

  import axios from 'axios'
  import { Message } from "element-ui"; // Introduce the element-UI message prompt component, as well as other popbox components
Copy the code

Context switching

   const isDev = process.env.NODE_ENV==='development';
   export const domain = isDev?'http://www.development.com':'http://www.production.com'; 
   // Export domain variables such as element- UI and upload components
   const service = axios.create({
      timeout: 10000.// Set the request timeout period
      baseURL: domain + "/api/" 
      // Set baseURL unless the url is/or an absolute path when the interface is called. Otherwise, the URL will be placed after baseURL
   });
Copy the code

Intercept request

Here the getToken function I use jS-cookie this package specific implementation code and localStorage syntax similar

 service.interceptors.request.use(
  config= > {
   // Add the token returned by the background to the request header;
  
   const token = getToken();
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    return config;
  },
  error= > {
    return Promise.reject(error); });Copy the code

Intercept the response

Let’s do something with the values that are returned to us in the background to avoid writing duplicate code

const ErrorMessage = {
  404: "Requested address error".403: "No access".500: "Server internal error".0: "Request timed out"}; service.interceptors.response.use((response) = > {
    // Destruct the assigned response object
    const { code, data,message } = response.data;
    if (code === 200) {
      return data;
    } else if (code === xxx||code===yyy) {
      errorMessage(message);
    }else if(code===401) {// If 401 is returned in the background, we can first clear the browser store token;
      // Then jump to login or another page
      // Redirect routes can import the VueRouter columns exported from router.js and implement the relevant logic with VueX
    }
    return Promise.reject(response);
  },
  (error) = > {
    const { status, data } = error.response;
    if (ErrorMessage[status]) {
      errorMessage(ErrorMessage[status]);
    } else {
      errorMessage(data.message);
    }
    return Promise.reject(error); });Copy the code

Export several common methods

export default service; // Export the service instance

export const post = service.post; // Export the POST method

export const get = service.get;// Export the get method


Copy the code

Use profile

  • Create an API folder under SRC to store our background interface address
  • A typical project created with vue-CLI will have a Webpack alias @ symbol pointing to the SRC path of the project.
  • Projects that are not built using vue-CLI can be configured by themselves in resolve. Alias in Webpack
import {post,get} from '@/utils/http.js';

// How to use get
export function a(params){
    return get('url',{
       params
    })
}

// Post usage
export function b(opt){
    return post('url',opt)
}
Copy the code