Axios detailed explanation and complete packaging method

I. What is axios

Axios is a promise-based network request library that works in node.js and browsers. It is isomorphic, that is, the same set of code can run in the browser and node.js. It uses the native node.js http module on the server side and XMLHttpRequests on the client side.

Axios has the following features:

Create XMLHttpRequests from Browser

Create http Request from node.js

Support for Promise API

Block requests and responses

Convert Request and Response Data

Cancel Request

Automatically convert JSON data

Client Support Defense XSRF

Methods that axios can request:

Get: Obtain data, request the specified information, and return the entity object.

Post: Submit data to a specified resource(Such as form submission or file upload)

Put: Updates data to replace the contents of the specified document from the client to the server

Patch: Update data. It is a supplement to the put method and is used to update a known resource locally.

Delete: Request the server to delete the specified data.

Head: Obtain the packet header

Request Method Alias

For convenience, axios provides alias: For all supported request methods

axios(config)

axios.request(config)

axios.get(url [,config])

axios.post(url [,data [,config]])

axios.put(url [,data [,config]])

axios.delete(url [,config])

axios.patch(url [,data [,config]])

axios.head(url [,config])

2. .axios instance and configuration method

1.Create axios Instance

axios.create([config])

Multiple axios instances can be created at the same time.

Sample Code

const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
}); 

Instance Method

The following are the available instance methods. The specified configuration is merged with the configuration of the instance.

axios#request(config)

axios#get(url[, config])

axios#delete(url[, config])

axios#head(url[, config])

axios#options(url[, config])

axios#post(url[, data[, config]])

axios#put(url[, data[, config]])

axios#patch(url[, data[, config]])

axios#getUri([config])

2.Configuration Method

Common configuration items for configuration objects:

These are the configuration options available when creating the request. Only url is required. If method is not specified, the request will use the GET method by default. See official documentation for more configuration items

{
  // pathurl
  url: '/user',

  // Request method,defaultget
  method: 'get', 

  //Baseurl,final requestedurlyes baseURL+urlSplicing,So set the default globally,This can be done when sending a requesturlbecome concise
  baseURL: 'https://some-domain.com/api/',

  //Set request header
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  //set requesturlofqueryparameter,can makeurlconcise。
  //for exampleurlyeshttps://some-domain.com/api/user  ThenparamsSet as follows,So finalurlyes:
  //https://some-domain.com/api/user?ID=12345&name=Jack
  params: {
    ID: 12345,
    name:"Jack"
  },

 //Set request body
  data: {
    firstName: 'Fred'
  },

  //Set another format for the request,But this is to set the string directly.
  data: 'Country=Brasil&City=Belo Horizonte',

 //Request timed out,Unit millisecond,default0,No timeout。
  timeout: 1000,

  //Response data type,defaultjson
  responseType: 'json', 

  //Encoding rules for response data,defaultutf-8
  responseEncoding: 'utf8',

    //Maximum length of response body 
  maxContentLength: 2000,

  // Maximum length of request body
  maxBodyLength: 2000,

  //Set the response status code to what is the success,transferresolve,Otherwise callrejectfail
  //The default is greater than or equal to200,less than300
  validateStatus: function (status) {
    return status >= 200 && status < 300; 
  }, 

Default Configuration

The global default configuration can be set to prevent multiple repeated configurations from being repeated in different requests, such as baseURL and timeout. Here, baseURL is set.

Global axios Default

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
"""
Custom instance default values

"""

// Configure default values ​​when creating an instance
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Modify the default value after creating the instance
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; 

Configured Priority

The configurations are merged by priority. The order is the library defaults found in lib/defaults.js, the defaults attribute of the instance, and the requested config parameter. The latter takes precedence over the preceding.

III. Interceptor

Custom axios instances can also be added to intercept requests or responses before they are processed by then or catch, such as:

const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/}); 

Request Blocker

Sample Code

// Add request interceptor
axios.interceptors.request.use(function (config) {
    // What to do before sending a request
    return config;
  }, function (error) {
    // What to do about request errors
    return Promise.reject(error);
  }); 

Response Blocker

Sample Code

 // Add response interceptor
axios.interceptors.response.use(function (response) {
    // 2xx Any status code within the range will trigger this function。
    // Do something with the response data
    return response;
  }, function (error) {
    // beyond 2xx This function will be triggered by any status code in the range。
    // Do something about the response error
    return Promise.reject(error);
  }); 

Unblocker

Sample Code

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor); 

IV. Cancellation Request

Note: Starting with v0.22.0, Axios supports fetch API – AbortController cancel request, CancelToken API deprecated

Here are two ways to use AbortController instead of CancelToken

AbortController

const controller = new AbortController();

axios.get('/foo/bar', {
   signal: controller.signal
}).then(function(response) {
   //...
});
// Cancel request
controller.abort() 

CancelToken

let source = axios.CancelToken.source();

axios.get('/users/12345',{
                cancelToken: source.token
            }).then(res=>{
                console.log(res)
            }).catch(err=>{
                //This method will be executed after canceling the request
                console.log(err)
            })

//Cancel request,Parameter optional,This parameter information will be sent to the requestedcatchmiddle
source.cancel('Information after cancellation'); 

You can also create a cancel token by passing a constructor of a executor function to a CancelToken

const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // executor The function receives a cancel function as parameter
    cancel = c;
  })
});

// Cancel request
cancel(); 

Note: Can cancel multiple requests using the same cancel token or signal

V. axios package

Start by designing what we want this generic request to do:

Optimize the configuration and set the default configuration items.(ResponseType. Cross-domain cookie, token, and timeout settings)

Unified setting request header

Set baseURL according to environment

Initiate a request directly through the Axios method

Add Request Blocker

Add Response Blocker

Export Promise Objects

Packaging Post Method, Reduced post Requests

Package the get method and streamline the get request mode.

The request succeeds. Configure the service status code.

Global loading Configuration

Package of axios in VUE

In the vue project, we usually use the axios library, which is a promise-based http library and can run in the browser and node.js. He has many excellent features, such as blocking requests and responses, canceling requests, converting json, defending the client against XSRF, and so on. So in particular, we resolutely abandoned the maintenance of our official library vue-resource and directly recommended us to use the axios library. If you still don’t know about axios, you can move axios documents.

Install

{
  // pathurl
  url: '/user',

  // Request method,defaultget
  method: 'get', 

  //Baseurl,final requestedurlyes baseURL+urlSplicing,So set the default globally,This can be done when sending a requesturlbecome concise
  baseURL: 'https://some-domain.com/api/',

  //Set request header
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  //set requesturlofqueryparameter,can makeurlconcise。
  //for exampleurlyeshttps://some-domain.com/api/user  ThenparamsSet as follows,So finalurlyes:
  //https://some-domain.com/api/user?ID=12345&name=Jack
  params: {
    ID: 12345,
    name:"Jack"
  },

 //Set request body
  data: {
    firstName: 'Fred'
  },

  //Set another format for the request,But this is to set the string directly.
  data: 'Country=Brasil&City=Belo Horizonte',

 //Request timed out,Unit millisecond,default0,No timeout。
  timeout: 1000,

  //Response data type,defaultjson
  responseType: 'json', 

  //Encoding rules for response data,defaultutf-8
  responseEncoding: 'utf8',

    //Maximum length of response body 
  maxContentLength: 2000,

  // Maximum length of request body
  maxBodyLength: 2000,

  //Set the response status code to what is the success,transferresolve,Otherwise callrejectfail
  //The default is greater than or equal to200,less than300
  validateStatus: function (status) {
    return status >= 200 && status < 300; 
  }, 

Introducing

Generally, I will create a new request folder in the src directory of the project, and then create a new http.js and a new api.js file in it. The http.js file is used to encapsulate our axios, and the api.js file is used to uniformly manage our interfaces.

// existhttp.jsintroduced inaxios
import axios from 'axios'; // introduceaxios
import QS from 'qs'; // introduceqsmodule,used to serializeposttype of data,Will be mentioned later
// vantoftoastPrompt box component,Everyone can base their ownuiComponent changes。
import { Toast } from 'vant'; 

Environment Handover

Our project environments may include development, test, and production environments. We match our default interface url prefix with the environment variable of node. The axios.defaults.baseURL can set the default request address of the axios.

// => environment switching
if (process.env.NODE_ENV == 'development') {    
    axios.defaults.baseURL = 'https://www.baidu.com';} 
else if (process.env.NODE_ENV == 'debug') {    
    axios.defaults.baseURL = 'https://www.ceshi.com';
} 
else if (process.env.NODE_ENV == 'production') {    
    axios.defaults.baseURL = 'https://www.production.com';
} 

Set Request Timeout

Set the default request timeout via axios.defaults.timeout. For example, if it exceeds 10 s, the user will be notified of the current request timeout. Please refresh.

axios.defaults.timeout = 10000; 

Settings for post request headers

When requesting a post, we need to add a request header. Therefore, you can set a default setting here, that is, set the request header of the post to application/x-www-form-urlencoded;charset=UTF-8.

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; 

Request Intercept

Before sending a request, we can intercept a request. Why do we intercept a request? What do we intercept a request for? For example, some requests need to be accessed after the user logs in, or when post requests are made, we need to serialize the data we submit. At this point, we can do what we want by intercepting the request before it is sent.

request interception
// Import firstvuex,Because we need to use the state object inside
// vuexThe path is written according to your own path
import store from '@/store/index';

// request interceptoraxios.interceptors.request.use( 
    config => {        
        // Check before sending each requestvuexDoes it exist intoken 
        // if it exists,then unified inhttpRequestedheaderAdd them alltoken,In this way, the background is based ontokenDetermine your login status
        // Even if it exists locallytoken,Also a possibilitytokenis expired,Therefore, the return status must be judged in the response interceptor 
        const token = store.state.token;        
        token && (config.headers.Authorization = token);        
        return config;    
    },    
    error => {        
        return Promise.error(error);    
}) 

To describe the token, after the login is completed, the token of the user is stored locally through the localStorage or the cookie. Then, each time the user enters the page (that is, in the main.js), the token is first read from the local storage. If the token exists, it indicates that the user has logged in, and the token status in the vuex is updated. Then, each time an interface is requested, the token is carried in the requested header. The background personnel can determine, according to the token carried by you, whether the login expires. If the token is not carried by you, it indicates that the login has not been performed. At this time, some small partners may have questions. Each request carries a token. What if a page can be accessed without user login? In fact, your front-end request can carry token, but the background can choose not to receive it!

Blocking Responses

// response interceptor
axios.interceptors.response.use(    
    response => {   
        // If the status code returned is200,Indicates that the interface request is successful,Data can be obtained normally 
        // Otherwise throw an error
        if (response.status === 200) {            
            return Promise.resolve(response);        
        } else {            
            return Promise.reject(response);        
        }    
    },    
    // The server status code is not2initial situation
    // Here you can negotiate with your backend developer about a unified error status code. 
    // Then perform some operations based on the returned status code,For example, login expiration prompt,Error message etc.
    // Here are some common operations:,Other needs can be expanded by yourself
    error => {            
        if (error.response.status) {            
            switch (error.response.status) {                
                // 401: Not logged in
                // If you are not logged in, you will be redirected to the login page.,And carry the path of the current page
                // Return to the current page after successful login,This step needs to be done on the login page。 
                case 401:                    
                    router.replace({                        
                        path: '/login',                        
                        query: { 
                            redirect: router.currentRoute.fullPath 
                        }
                    });
                    break;

            // 403 tokenExpired
            // Prompt user when login expires
            // clear localtokenand clearvuexmiddletokenobject
            // Jump to login page 
            case 403:
                 Toast({
                    message: 'Login expired,please login again',
                    duration: 1000,
                    forbidClick: true
                });
                // Cleartoken
                localStorage.removeItem('token');
                store.commit('loginSuccess', null);
                // Jump to login page,and the page to be viewedfullPathPass it over,After successful login, jump to the page you need to visit. 
                setTimeout(() => {                        
                    router.replace({                            
                        path: '/login',                            
                        query: { 
                            redirect: router.currentRoute.fullPath 
                        }                        
                    });                    
                }, 1000);                    
                break; 

            // 404Request does not exist
            case 404:
                Toast({
                    message: 'The network request does not exist',
                    duration: 1500,
                    forbidClick: true
                });
                break;
            // Other errors,Throw an error message directly
            default:
                Toast({
                    message: error.response.data.message,
                    duration: 1500,
                    forbidClick: true
                });
        }
        return Promise.reject(error.response);
    }
}    
}); 

The response interceptor understands that it is the data that the server returns to us, and we can do some processing to him before we get it. For example, the above thought: If the status code returned by the background is 200, the data is returned normally. Otherwise, some errors are required according to the error status code type. In fact, the error is processed uniformly and the login page is adjusted after no login or login expiration.

Note that the above Toast method is the toast light prompt component in the vant library I introduced. You use one of your prompt components according to your ui library.

Package get Method and post Method

We often use ajax request methods such as get, post, and put. We believe that none of our partners is new. There are many similar methods corresponding to the axios. You can see the documents if you are not clear. But to simplify our code, we still have to do a simple package. Here are two main packaging methods: Get and post.

Get method: We define a get function. The get function has two parameters. The first parameter indicates the url address we want to request, and the second parameter indicates the request parameter we want to carry. The get function returns a promise object. When the request of the axios succeeds, the resolve server returns the value, and when the request fails, the reject error value. Finally, the get function is thrown through export.

/**
 * getmethod,correspondgetask
 * @param {String} url [Requestedurladdress]
 * @param {Object} params [Parameters carried when requesting]
 */
export function get(url, params){    
    return new Promise((resolve, reject) =>{        
        axios.get(url, {            
            params: params        
        }).then(res => {
            resolve(res.data);
        }).catch(err =>{
            reject(err.data)        
    })    
});} 

Post method: The principle is basically the same as that of the get, but it should be noted that the post method must use the operation of serializing the submitted slave parameter object. Therefore, we serialize our parameters through the qs module of the node. This is important. Without serialization, the background will not get the data you submitted. That’s why we import QS from ‘qs’; started the article. If you don’t understand what serialization means, Baidu, a lot of answers.

/** 
 * postmethod,correspondpostask 
 * @param {String} url [Requestedurladdress] 
 * @param {Object} params [Parameters carried when requesting] 
 */
export function post(url, params) {
    return new Promise((resolve, reject) => {
         axios.post(url, QS.stringify(params))
        .then(res => {
            resolve(res.data);
        })
        .catch(err =>{
            reject(err.data)
        })
    });
} 

Here’s a small detail, the axios.get method is different from the axios.post method in how parameters are written when submitting data. The difference is that the second parameter of get is a, and then the value of the params attribute of this object is a parameter object. The second parameter of post is a parameter object. Pay attention to the slight difference!

The package of the axios is basically completed. The following briefly describes the unified management of the api. A neat api is like a circuit board, and even more complex can make the entire line clear. As mentioned above, we will create a new api.js and store all our api interfaces in this file.

First we introduce our packaged get and post approach to api.js

/**   
 * apiUnified management of interfaces
 */
import { get, post } from './http'
Now,For example, we have an interface like this,Is apostask:

http://www.baiodu.com/api/v1/users/my_address/address_edit_before
we canapi.jsEncapsulated like this:

export const apiAddress = p => post('api/v1/users/my_address/address_edit_before', p);
We defined aapiAddressmethod,This method has a parameterp,pIt is the parameter object we carry when requesting the interface.。Then we called our encapsulatedpostmethod,postThe first parameter of the method is our interface address,The second parameter isapiAddressofpparameter,That is, the parameter object carried when requesting the interface。finally passedexportExportapiAddress。

Then in our page we can call ourapiinterface:

import { apiAddress } from '@/request/api';// Import ourapiinterface
export default {        
    name: 'Address',    
    created () {
        this.onLoad();
    },
    methods: {            
        // retrieve data 
        onLoad() {
            // transferapiinterface,and provides two parameters 
            apiAddress({                    
                type: 0,                    
                sort: 1                
            }).then(res => {
                // Other operations after successfully obtaining data
                ………………                
            })            
        }        
    }
} 

Other api interfaces can be extended in the pai.js. Friendly tips, write notes for each interface!!!

One of the benefits of api interface management is that we unify and centralize the api. If we need to modify the interface in the later stage, we will find the corresponding modification in the api.js directly, instead of searching our interface on each page and modifying it. The key is, in case the modification ratio is larger, the specification is gg. In addition, if the interface is modified directly in our service code, it is easy to move our service code to cause unnecessary trouble.

Okay, and finally, the completed axios package code.

/**axiosencapsulation
 * request interception、Corresponding interception、Unified handling of errors
 */
import axios from 'axios';import QS from 'qs';
import { Toast } from 'vant';
import store from '../store/index'

// environment switching
if (process.env.NODE_ENV == 'development') {    
    axios.defaults.baseURL = '/api';
} else if (process.env.NODE_ENV == 'debug') {    
    axios.defaults.baseURL = '';
} else if (process.env.NODE_ENV == 'production') {    
    axios.defaults.baseURL = 'http://api.123dailu.com/';
}

// Request timeout
axios.defaults.timeout = 10000;

// postRequest header
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

// request interceptor
axios.interceptors.request.use(    
    config => {
        // Check whether it exists before each request is sent.token,if it exists,then unified inhttpRequestedheaderAdd them alltoken,No need to add it manually for every request
        // Even if it exists locallytoken,Also a possibilitytokenis expired,Therefore, the return status must be judged in the response interceptor
        const token = store.state.token;        
        token && (config.headers.Authorization = token);        
        return config;    
    },    
    error => {        
        return Promise.error(error);    
    })

// response interceptor
axios.interceptors.response.use(    
    response => {        
        if (response.status === 200) {            
            return Promise.resolve(response);        
        } else {            
            return Promise.reject(response);        
        }    
    },
    // The server status code is not200Case 
    error => {        
        if (error.response.status) {            
            switch (error.response.status) {                
                // 401: Not logged in 
                // If you are not logged in, you will be redirected to the login page.,And carry the path of the current page 
                // Return to the current page after successful login,This step needs to be done on the login page。 
                case 401:                    
                    router.replace({                        
                        path: '/login',                        
                        query: { redirect: router.currentRoute.fullPath } 
                    });
                    break;
                // 403 tokenExpired 
                // Prompt user when login expires 
                // clear localtokenand clearvuexmiddletokenobject 
                // Jump to login page 
                case 403:                     
                    Toast({                        
                        message: 'Login expired,please login again',                        
                        duration: 1000,                        
                        forbidClick: true                    
                    });                    
                    // Cleartoken 
                    localStorage.removeItem('token');                    
                    store.commit('loginSuccess', null);                    
                    // Jump to login page,and the page to be viewedfullPathPass it over,After successful login, jump to the page you need to visit.
                    setTimeout(() => {                        
                        router.replace({                            
                            path: '/login',                            
                            query: { 
                                redirect: router.currentRoute.fullPath 
                            }                        
                        });                    
                    }, 1000);                    
                    break; 
                // 404Request does not exist 
                case 404:                    
                    Toast({                        
                        message: 'The network request does not exist',                        
                        duration: 1500,                        
                        forbidClick: true                    
                    });                    
                break;                
                // Other errors,Throw an error message directly 
                default:                    
                    Toast({                        
                        message: error.response.data.message,                        
                        duration: 1500,                        
                        forbidClick: true                    
                    });            
            }            
            return Promise.reject(error.response);        
        }       
    }
);
/** 
 * getmethod,correspondgetask 
 * @param {String} url [Requestedurladdress] 
 * @param {Object} params [Parameters carried when requesting] 
 */
export function get(url, params){    
    return new Promise((resolve, reject) =>{        
        axios.get(url, {            
            params: params        
        })        
        .then(res => {            
            resolve(res.data);        
        })        
        .catch(err => {            
            reject(err.data)        
        })    
    });
}
/** 
 * postmethod,correspondpostask 
 * @param {String} url [Requestedurladdress] 
 * @param {Object} params [Parameters carried when requesting] 
 */
export function post(url, params) {    
    return new Promise((resolve, reject) => {         
        axios.post(url, QS.stringify(params))        
        .then(res => {            
            resolve(res.data);        
        })        
        .catch(err => {            
            reject(err.data)        
        })    
    });
} 

The package of the axios varies according to different requirements.

1.Optimized axios package with previous get and post removed

2.Network Disconnection Handling

3.More modular api management

4.Multiple interface domain names

5.Omitting Introduced Steps on api Mount to vue.prototype

To optimize the axios package in http.js, paste the code directly:

/**
 * axiosencapsulation
 * request interception、response interception、Unified handling of errors
 */
import axios from 'axios';
import router from '../router';
import store from '../store/index';
import { Toast } from 'vant';

/** 
 * prompt function 
 * Disable clicking on the mask、Shows for one second and then closes
 */
const tip = msg => {    
    Toast({        
        message: msg,        
        duration: 1000,        
        forbidClick: true    
    });
}

/** 
 * Jump to login page
 * Carrying the current page route,In order to return to the current page after completing the login on the login page
 */
const toLogin = () => {
    router.replace({
        path: '/login',        
        query: {
            redirect: router.currentRoute.fullPath
        }
    });
}

/** 
 * Unified handling of errors after failed requests 
 * @param {Number} status Request failed status code
 */
const errorHandle = (status, other) => {
    // Status code judgment
    switch (status) {
        // 401: Not logged in,Jump to login page
        case 401:
            toLogin();
            break;
        // 403 tokenExpired
        // Cleartokenand jump to the login page
        case 403:
            tip('Login expired,please login again');
            localStorage.removeItem('token');
            store.commit('loginSuccess', null);
            setTimeout(() => {
                toLogin();
            }, 1000);
            break;
        // 404Request does not exist
        case 404:
            tip('The requested resource does not exist'); 
            break;
        default:
            console.log(other);   
        }}

// createaxiosExample
var instance = axios.create({    timeout: 1000 * 12});
// set uppostRequest header
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
/** 
 * request interceptor 
 * before each request,if it existstokenis carried in the request headertoken 
 */ 
instance.interceptors.request.use(    
    config => {        
        // Login process under control,Depending on whether it exists locallytokenDetermine the user's login status 
        // But even iftokenexist,Also a possibilitytokenis expired,Therefore, it is carried in each request headertoken 
        // The background is based on the carriedtokenDetermine the user's login status,And return us the corresponding status code 
        // Then we can use the response interceptor,Perform some unified operations based on the status code。 
        const token = store.state.token;        
        token && (config.headers.Authorization = token);        
        return config;    
    },    
    error => Promise.error(error))

// response interceptor
instance.interceptors.response.use(    
    // Request successful
    res => res.status === 200 ? Promise.resolve(res) : Promise.reject(res),    
    // Request failed
    error => {
        const { response } = error;
        if (response) {
            // Request sent,but not there2xxrange 
            errorHandle(response.status, response.data.message);
            return Promise.reject(response);
        } else {
            // Handle disconnection situations
            // eg:When the request times out or the network is disconnected,renewstateofnetworkstate
            // networkThe status isapp.vueControls the display and hiding of a global disconnection prompt component
            // About refreshing and re-obtaining data in disconnected components,Will be explained in the disconnection component
            if (!window.navigator.onLine) {
               store.commit('changeNetwork', false);
            } else {
                return Promise.reject(error);
            }
        }
    });

export default instance; 

This axios is similar to the previous one. The following changes have been made:

1.The encapsulation of the previous get and post methods is removed, and it is more flexible to use by creating a axios instance and then exporting the export default method.

2.The value that controls the baseUrl through the environment variable is removed. Considering that the interface will have multiple different domain names, it is prepared to control the interface domain name through the js variable. This is covered in api.

3.The processing of the request timeout, that is, the disconnection status, is added. In this way, when the network is disconnected, the display of the disconnection prompt component is controlled by updating the status of the network in the vuex. The disconnection prompt usually reloads data. This step is described later.

4.Common functions are extracted, codes are simplified, and the principle of single responsibility is ensured as much as possible.

Let’s talk about api and consider the following:

1.More modular

2.Easier multi-person development and reduced naming conflicts

3.There are multiple scenarios for handling interface domain names

Here, a new api folder is created, which contains a index.js and a base.js, and several interface js files divided according to the module. Index.js is the egress of a api, and the domain name of the base.js management interface. Other js are used to manage the interfaces of various modules.

Put the index.js code first

/** 
 * apiUnified export of interface
 */
// Article module interface
import article from '@/api/article';
// Interfaces to other modules……

// Export interface
export default {    
    article,
    // ……
}
index.jsIs aapiinterface exit,This way you canapiThe interface is divided into multiple modules according to functions,Conducive to multi-person collaborative development,For example, one person is only responsible for the development of one module, etc.,It also facilitates the naming of interfaces in each module.。

base.js:

/**
 * Management of interface domain names
 */
const base = {    
    sq: 'https://xxxx111111.com/api/v1',    
    bd: 'http://xxxxx22222.com/api'
}

export default base;
passbase.jsTo manage our interface domain name,No matter how many there are, you can define the interface here。Even if it is modified,It is also very convenient。

Finally, the description of the interface module,For example the abovearticle.js:

/**
 * articleModule interface list
 */

import base from './base'; // Import interface domain name list
import axios from '@/utils/http'; // importhttpcreated inaxiosExample
import qs from 'qs'; // Whether to import according to requirementsqsmodule

const article = {    
    // news list 
    articleList () {        
        return axios.get(`{base.sq}/topics`);       },       // News details,Demo    articleDetail (id, params) {               return axios.get(`{base.sq}/topic/{id}`, {                       params: params               });       },
    // postsubmit    login (params) {               return axios.post(`{base.sq}/accesstoken`, qs.stringify(params));    
    }
    // Other interfaces…………
}

export default article; 

1.By directly introducing the encapsulated axios instance, defining the interface, invoking the axios instance, and returning it, you can use the axios more flexibly. For example, you can perform qs serialization on the data submitted during the post request.

2.The requested configuration is more flexible and you can make a different configuration for a requirement. The axios document makes it clear that the priority of the configuration is the default value of the library found in lib/defaults.js, the defaults attribute of the instance, and the config parameter of the request. The latter will take precedence over the former.

3.The restful-style interface can also flexibly set the api interface address in this way.

Finally, to facilitate the call to api, we need to mount it on the prototype of vue. In main.js

import Vue from 'vue'
import App from './App'
import router from './router' // Import routing file
import store from './store' // importvuexdocument
import api from './api' // importapiinterface

Vue.prototype.api = api; // Willapimount tovueon the prototype
Then we can call the interface like this in the page,eg:

methods: {       onLoad(id) {             this.api.article.articleDetail(id, {        
            api: 123      
        }).then(res=> {
            // perform some action 
        })    
    }  
} 

Refer to the disconnection processing. Here is only a simple example:

I’m out of network

This is app.vue. Here’s a simple demonstration of disconnection. In the http.js, we update the network status in the vue when the network is disconnected. In this case, we determine whether to load the disconnected component according to the network status. When the network is disconnected, load the disconnected component without loading the component on the corresponding page. When you click Refresh, you can reacquire the data by jumping to the refesh page and returning immediately. So we need to create a new refresh.vue page and return to the current page in its beforeRouteEnter hook.

// refresh.vue
beforeRouteEnter (to, from, next) {
    next(vm => {            
        vm.$router.replace(from.fullPath)        
    })    
} 

This document is transferred from https://blog.csdn.net/zrblue/article/details/135318200,If there is any infringement,Please contact to delete。