1. Axios concept

Axios: Ajax library based on Promise encapsulation (core or Ajax four steps)

  • Ajax requests are generally asynchronous
    • Ajax serialization: the first interface request succeeds before proceeding to the second request…
    • Ajax parallelism: Sending multiple interface requests at the same time, and then executing something when all interface requests are successful => Promise.all
  • Manages ajax asynchronous operations based on promises

Fetch: New API for the browser that is promise-based by default (not XMLHttpRequest at its core)

// The traditional scenario causes callback hell
$.ajax({
    url: 'http://127.0.0.1/api1'.success: result= > {
        $.ajax({
            url: 'http://127.0.0.1/api2'.success: result= >{... }})}})Copy the code
// Return a PROMISE instance
axios.get('http://127.0.0.1/api1').then(response= > {
    return axios.get('http://127.0.0.1/api2');
}).then(response= >{... })Copy the code

2. Axios Learning directory

  • Basic use of Axios

  • Secondary encapsulation of Axios

    • The interceptor
    • Some general configurations

    1. Basic use of Axios

// All Promise instances are returned
axios([config])
axios([url], [config])
axios.get/head/delete/options([url], [config])
axios.post/put([url], [data], [config])
Copy the code
/ / axios. Get use
let baseUrl = 'http://127.0.0.1';
axios.get('/api1', {
    baseUrl,  // The public part of the requested address: the last requested address baseUrl + URL
    headers: {
        'Content-Type': 'application-www-form-urlencoded'
    }, // Customize the request header
    timeout: 0.// Whether to allow resource credentials in CORS cross-domain requests
    responseType: 'json'.// Set the data content to return from the server: what or what the server should return (the format is determined in the background),
    // The default means to process the result returned by the server into the desired data format. Supported formats are: 'arrayBuffer ',' blob','document','json','text','stream')
    validateStatus: function(status){
        return status >= 200  && status <= 300;
    }, // It specifies which status code in the result of a request represents success and which represents failure, thus determining whether to execute then or catch
    params: {
        name: 'luban'.age: 4
    }// Get requests pass parameters, which are concatenated to the end of the URL (must be a plain object or URLSearchParams object).
}).then(response= > {
    // The object was successfully obtained from the server
    //status/statusText: description of the status code
    // Request: native XHR object
    //headers: Stores partial response headers
    //config: we send the configuration item for the request
    //data: the server responds to the body (the data we get)
    return response.data;
}).catch(reason= > {
    // Obtain the failed data from the server
    // Return an instance of the ERROR class
    //message: error message
    // Request: native XHR object
    //config: we send the configuration item for the request
    //response: response is equivalent to a successful response, but there may be no response. If you send a request to the server, the server receives it, but returns a status code that does not start with 2 (although it failed, but at least tells us the specific result), this is a response. If the request does not reach the server (for example, the network is disconnected), there is no response
    console.log('failure');
    return Promise.reject(reason.message);
}).then(result= > {
    //result = response.data
    console.log('Response body information', result);
})
Copy the code
axios.post('/user/update', {
    userId: 1.desc: 'Lu Ban is so cute'
}, {
    baseUrl,
    // Post is based on the information passed to the server by the request body
    /* Format: form-data/x-www-from-urlencoded/raw/binary/GraphQL form-data: content-type: multipart/form-data x-www-from-urlencoded: xxx=xxx&xxx=xxx application/x-www-from-urlencoded raw: Text format: "plain text" "JSON string Application /json" Binary: Application /octet-stream */
    
    headers: {
        "Content-type": "application/x-www-from-urlencoded"
    },
    //transformRequest: Transform the message sent by the request body into the format we want before sending it to the server
    transformRequest: data= > {
        // Data is the object we configure
        returnQs.stringify(data); }})Copy the code

2. Axios’s secondary encapsulation

/* - Axios library default configuration - extracted public parameter configuration axios.defaults - sent request write configuration separately, axios.get([url], [config]) priority bottom up */

// Requirement 1: In a real project, we might control the address prefixes differently based on environment variables (start/test/production)
let env = process.env.NODE_ENV; // Get the environment variable configured in webpack/package.json
switch(env) {
    case "production": 
        axios.defaults.baseURL = "http://xxx.x.x.x/xxxx";
        break;
    case "test": 
        axios.defaults.baseURL = "http://xxx.x.x.x/xxxx";
        break;
    default:
        axios.defaults.baseURL = "http://xxx.x.x.x/xxxx";
}

Copy the code
axios.defaults.baseURL = "http://127.0.0.1/8080";
axios.defaults.timeout = 10000;
axios.defaults.withCredentials = true;
axios.defaults.headers = {
    "Content-type": "application/x-www-from-urlencoded"
}
axios.defaults.transformRequest = data= > Qs.stringify(data);
axios.defaults.validateStatus = status= > (status >= 200  && status <= 300);
// Request interceptor: intercepts the config we set and reconfigures it before we send the data to the server
axios.interceptors.request.use(config= > {
    //config: stores existing configuration items
    
    / / carry a token
    let token = localStorage.getItem('token');
    token && (config.headers.Authorization = token);
    return config;
});
// Respond to interceptors
axios.interceptors.response.use(response= > {
    //response: the result returned successfully
    return response.data;
}, reason= > {
    // Failed to return the information
    // For the result of failure to do different prompt for the latter processing
    if (reason.response) {
        // The server returns a message, except that the status code does not start with 2
        switch(reason.response.status) {
            case 401:
                // Permission issues
                break;
            case 403:
                / / Token expired
                break;
            case 404:
                // The address is incorrect
                break; }}else {
        // Check whether the network is disconnected
        if(! navigator.onLine) { } }return Promise.reject(reason.message);
});
Copy the code