With axios always feel inexplicable this and that wrong, a simple summary.

The CDN address is https://unpkg.com/[email protected]/dist/axios.min.js, the version number can be changed, no version number is the latest release. But these days, a lot of times NPM I Axios will do.

Key steps to use Axios:

  1. Create an instance of Axios so that you can put the common configuration here, such asinstance.jsTo handle all kinds of exceptions
  2. Each API should be written separately. If many apis are written in a folder, the related APIS can be written in a file, or if fewer apis are written in a fileapi.js
  3. Make the API global, so that when you use it, you don’t need to import the interfacethis.api.apiName()

You must first understand content-type

Get request does not exist Set content-type. Only post and PUT use content-type, the usual post method, so I’ll focus on POST. The content-type of post has three types:

  • Axios. Post (URL,{a:1,b:2}) and the second argument is an object

  • Content-type: application/x-www-form-urlencoded for AXIos, post time let data = {a:1,b:2}; Axios.post (URL,qs.stringify({data})), which defaults when the second argument is a string

  • Content-type: multipart/form-data For AXIos, let data = new FormData(); data.append(‘a’,1′); data.append(‘b’,2); Axios.post (URL,data) defaults to this type if the argument is formData, and defaults to this type if it is submitted using the form’s built-in action

The server will resolve these three methods in different ways, with particular attention to !!!!!

In other words, content-type will automatically have the corresponding value according to the type of parameters, generally do not need to set ~~~, but, in some cases, I want to pass object, but the actual server needs is application/ X-wwW-form-urlencoded, [function (data) {return qs.stringify (data)}],

Here summary, the above explanation read several times, I reflect arc long, it takes a long time to roughly understand what is said.

Create an instance of Axios

Here is the sample code.

/** * Axios encapsulates request interception, response interception, and uniform error handling */
import axios from 'axios';

// Create the Axios instance
var instance = axios.create({    timeout: 1000 * 12});
/** * Request interceptor * carries the token */ in the request header if it exists before each request 
instance.interceptors.request.use(    
    config= > {        
        // You can add uniform parameters, such as appID, token and so on
    },    
    error => Promise.error(error)
)

// Respond to interceptors
instance.interceptors.response.use(    
    // The request succeeded
    res => res.status === 200 ? Promise.resolve(res) : Promise.reject(res),    
    // The request failed
    error => {
        const { response } = error;
        if (response) {
            // The request has been sent, but it is not in the range of 2xx, and the background will determine some error code and handle the error
            errorHandle(response.status, response.data.message);
            return Promise.reject(response);
        } else {
            // None of the requests were sent
            // Handle the case of network disconnection
            if (!window.navigator.onLine) {
               // Disconnect the Internet
            } 
            return Promise.reject(error); }});export default instance;
Copy the code

Each API is written separately

// api.js
// Pass the parameters as objects, so that the parameters do not need to be sorted
const ajaxKeMuData = ({ wind, projectSname = "" }) = >
  instance.post('/keMuXuBanRate', {
    wind,
    projectSname
  });
export {
    ajaxKeMuData
}

Copy the code

Make the API global

Finally, it is added to the global, if this is the vUE project

// main.js
import api from './api' // Import API interface
Vue.prototype.$api = api; // Mount the API to vue's prototype

Copy the code

This.$API. AjaxKeMuData ({… }).then(…)

The last

It’s sketchy, and there’s some work to be done, but for more details see axios’s great article, especially in the updates section

Good article from Axios, especially the explanation of content-type in the update