Axios introduction

1. What is Axios?

Axios is a Promise based HTTP library, similar to jQuery’s Ajax, for HTTP requests. It can be used in browsers and Node.js, either as a client or as a node.js-written server.

2. Axios features

(1) Support Promise API

(2) Intercepting requests and responses, such as doing something before adding authorization and response to a request.

(3) Conversion of request data and response data, such as request encryption or response data encryption.

(4) Cancel the request

(5) Automatically convert JSON data

(6) The client supports XSRF defense

3. Browser support

Firefox, Chrome, Safari, Opera, Edge, IE8+.


Axios is basically used

yarn add axios
Copy the code
import axios from "axios"
axios.get("/data.json").then(res=>{
    console.log(res)
}).catch(err=>{
    console.log(err)
})
Copy the code

Open up the console and take a look. I’ve got data


Axios uses the request method

Methods include get, POST, PUT, patch, and delete.

  • Get: Common users obtain data
  • Post: generally used for form submission and file uploading
  • Patch: Update data (only push modified data to the back end)
  • Put: Updates data (all data is pushed to the server)
  • Delete: deletes data

Note: POST is used to create data, PUT is used to update data, and patch is used to update data when there is a large amount of data.

1. Get method

Methods a

axios
      .get("/data.json", { 
        params: { 
          id: 12
        }
      })
      .then(res => { 
        console.log(res);
      })
      .catch(err => { 
        console.log(err);
      });
Copy the code

Way 2

axios({ 
      method: "get",
      url: "/data.json",
      params:{ 
          id:12
      }
    }).then(res => { 
      console.log(res);
    });
Copy the code

The get request with parameters is actually http://xxxxx/data.json? If id=12, I’m going to write so much that the result is **url with the argument **.

Browser console information:

  1. Request URL: indicates the Request URL
  2. Request Method: indicates the Request Method

2. Post method

Post requests There are two common data request formats:

1. Form-data (often used for form submission (image upload, file upload))

let data = {
  id: 12
};
let formData = new FormData();
for(let key in data){ 
  formData.append(key,data[key])
}
console.log(formData)
axios.post('/data.json',formData).then(res=>{ 
  console.log(res,'formData')
})
Copy the code

Request URL: http://xxxxxxx/data.json,

Content-type: multipart/form-data; A boundary = – WebKitFormBoundarydgohzXGsZdFwS16Y

Parameter Format: ID :12

2. Application /json (common)

Methods a

let data = {

  id: 12
};
axios.post("/data.json", data).then(res=>{ 
  console.log(res, 'post')
});
Copy the code

Way 2

let data = {
  id: 12
};
axios({ 
  method:'post',
  url:'/data.json',
  data:data
}).then(res=>{ 
  console.log(res)
})
Copy the code

Note: Request to address the Request URL: http://xxxxxxxx/data.json,

Content-type: application/json; charset=UTF-8

Parameter Format: {id:12}

3, put method

let data = { 
    id: 12
};
axios.put("/data.json", data).then(res=>{ 
    console.log(res, 'put')
});
Copy the code

4. Patch method

let data = { 
  id: 12
};
axios.patch("/data.json", data).then(res=>{ 
  console.log(res, 'patch')
});
Copy the code

5. Delete method

Method 1: Params

axios
      .delete("/data.json", { 
        params: { 
          id: 12
        }
      })
      .then(res => { 
        console.log(res, "delete");
      });
let params = { 
      id: 12
    };
    axios({ 
      method:'delete',
      url:'/data.json',
      params:params
    }).then(res=>{ 
      console.log(res)
    })
Copy the code

Method 2: Data

axios
      .delete("/data.json", { 
        data: { 
          id: 12
        }
      })
      .then(res => { 
        console.log(res, "delete");
      });
let data = { 
      id: 12
    };
    axios({ 
      method:'delete',
      url:'/data.json',
      data:data
    }).then(res=>{ 
      console.log(res)
    })
Copy the code

Note: params way will Request parameter splicing in the URL above, the Request URL: http://xxxxxxxx/data.json? id=12

Parameter Format: ID :12

Content-Type: text/html; charset=utf-8

Data does not speak in a parameter, is placed directly in the Request body, the Request URL: http://xxxxxxxx/data.json

Parameter Format: {id:12}

Content-Type: application/json; charset=UTF-8

(1) Use an alias: axios.get(); (2) Do not use aliases like axios();

6. Concurrent requests

A concurrent request is one in which multiple requests are made simultaneously and the return value is processed uniformly. A similar promise. All.

In the following example, we use axios.all to request data.json/city.json simultaneously, and use axios.spread to process the returned results separately. The code is as follows:

All ([axios.get("/data.json"), axios.get("/city.json")]). Then (axios.spread((dataRes, cityRes) => { console.log(dataRes, cityRes); }));Copy the code

Note: The argument to axios.all is an array of request functions. In the corresponding callback then, call axios.spead to process the return value.

Concurrent requests can be used when multiple requests need to be made simultaneously and the return value of the interface call needs to be processed simultaneously.


Axio instance

1. Create an axios instance

For example, if there are multiple back-end interface addresses (www.test.com and www.example.com) and the timeout duration is different (1000ms and 2000ms), you can create an instance.

The configuration roadmap is as follows: Create multiple instances, configure different timeout periods, and use different instances to request different interfaces. Use axios.acreate to create instances, configure information, and make network requests. The code is as follows:

Let instance = axios.create({baseURL:'http://loacalhost:8080', Get ('/data.json'). Then (res=>{console.log(res)})  "http://loacalhost:8081", timeout: 2000 }); instance2.get("/city.json").then(res => { console.log(res); });Copy the code

Note: at this time, we can access the interfaces of http://loacalhost:8080 and http://loacalhost:8081 with different configurations.

2. Configuration of axiOS instances

(1) Configure the list

  • BaseURL: Requested domain name (base address).

  • Timeout: indicates the timeout period of the request. If the timeout period is exceeded, the backend returns 401.

    Note: Generally, the request is defined by the backend. If the processing time of the back-end interface is long, the backend cannot process the request, and the request will be blocked, causing heavy pressure on the server. After setting, you can release it in time.

  • Url: request path.

  • Method: request method. For example, get, POST, PUT, Patch, and delete.

  • Headers: request head.

  • Params: Concatenates the request parameters to the URL

  • Data: Places the request parameters in the request body

Axios.create ({baseURL: ", // request domain name (basic address) timeout:2000, // request timeout duration, in milliseconds, default. Json: // request method:'get', // request method: headers:{token:''},// request method params:{},// // Put the request parameters in the request body});Copy the code

(2) Three configuration modes

  • Axios global configuration
Axios.defaults.baseurl = 'http://localhost:8080' axios.defaults.timeout = 2000Copy the code
  • Axios instance configuration
let instance = axios.create();

instance.defaults.timeout = 3000
Copy the code
  • Axios requests configuration
The instance. The get ('/data. Json, '{timeout: 5000})Copy the code

Priority: AXIOS global configuration < AXIOS instance configuration < AXIOS request configuration

3. Usage of common parameter configuration

Example 1:

let instance1 = axios.create({ 
        baseURL:'http://localhost:9090',
        timeout:1000
    })
    instance1.get("/contactList",{ 
        params:{ 
            id:10
        }
    }).then(res=>{ 
        console.log(res)
    })
Copy the code

BaseURL: ‘http://localhost:9090’, timeout:1000, method: ‘get’, params:\{id:10}, url: ‘/contactList’

Example 2:

let instance2 = axios.create({ 
        baseURL:'http://localhost:9091',
        timeout:3000
    })
    instance2.get("/contactList",{ 
        timeout:5000
    }).then(res=>{ 
        console.log(res)
    })
Copy the code

BaseURL: ‘http://localhost:9091’, timeout:5000, method: ‘get’, url: ‘/contactList’

Note: The final effective configuration is overwritten by the high priority over the low priority.


Axios interceptors, error handling, and cancellation requests

1. Interceptors

What is an interceptor?

Intercepting requests or responses before they are processed comes in two types: request interceptors and response interceptors.

How interceptors are used

Request interceptor

/ / request interceptor axios. Interceptors. Request. Use (config = > {/ / do something before send the request return config. }, err=>{// Return promise.reject (err)});Copy the code

Response interceptor

/ / response interceptor axios. Interceptors. Response. Use (res = > {/ / data processing after the request is successful return res; }, err=>{// Return promise.reject (err)});Copy the code

Cancel interceptor

let inter = axios.interceptors.request.use(config=>{

    config.header={ 
        auth:true
    }
    return config
})
axios.interceptors.request.eject(inter)
Copy the code

Example A: Login permission

Interface instance that requires a token

let instance = axios.create({ });
instance.interceptors.request.use(config=>{ 
    config.headers.token = '';
    return config
})
Copy the code

Interface instance that does not require a token

let newInstance = axios.create({ });
Copy the code

Example B: Data loading animation for mobile terminal development

Instance_phone = axios.create({}); instance_phone.interceptors.request.use(config=>{ $('#loading').show(); return config }) instance_phone.interceptors.response.use(res=>{ $('#loading').hide(); return res })Copy the code

Note: The loading animation is displayed when data is requested and hidden when data is responded.

2, error handling, interception

In combination with the request interceptor and the response interceptor, the catch method is executed regardless of the request or response error.

/ / request interceptor axios. Interceptors. Request. Use (config = > {/ / do something before send the request return config. }, err => {return promise.reject (err); }); / / response interceptor axios. Interceptors. Response. Use (res = > {/ / data processing after the request is successful return res; }, err => {// Return promise.reject (err); }); axios .get("data.json") .then(res => { console.log(res); }) .catch(err => { console.log(res); });Copy the code

Error Handling Examples

In real development, instead of using the catch method every time a network request is made, a unified error handling method can be added. The code is as follows:

Let instance = axios.create({}); instance.interceptors.request.use( config => { return config; }, err => {4XX 401- Request timeout 404-mot found $("#error").show(); setTimeout(()=>{ $("#error").hide(); }, 2000) return Promise.reject(err); }); / / response error handling the instance. The interceptors. Response. Use (res = > {return res; }, err => {// Common status code for response error 5XX 500- server error 502- server restart $("#error").show(); setTimeout(()=>{ $("#error").hide(); }, 2000) return Promise.reject(err); }); Instance.get ("/data.json").then(res=>{console.log(res,' request successful ')}).catch(err=>{console.log(err,' other than interceptor set processing ')})Copy the code

First, create an instance and set request interceptor and response interceptor for the instance.

  • (1) Common status codes of request errors begin with 4, such as 401- request timeout, 404- interface not found;
  • (2) Common status codes for response errors start with 5, such as 500-server error, 502-server restart, etc.
  • (3) In addition to setting the request interceptor and response interceptor, we can use the catch method at the time of the request if we need other operations.

3. Cancel the request (uncommon)

let source = axios.CancelToken.source(); axios .get("/data.json", { cancelToken: source.token }) .then(res => { console.log(res); }). Catch (err=>{console.log(err)}) // Cancel the request source.cancel(' custom string optional ')Copy the code

Application scenarios

When the data is not retrieved for a long time (3-5s), the request needs to be cancelled.

Encapsulation and use of AXIos requests

Thought analysis

The encapsulation of axios requests is nothing more than code management, where we can use the decouple idea of processing the interfaces of different functional modules into different modules and encapsulating a method dedicated to data interaction.

Step 1: Create a new onesrc/service/contactApi.jsfile

Const CONTACT_API = {getContactList:{method:'get', url:'/contactList'}, Form-data newContactForm:{method:'post', url:'/contact/new/form'}, Application /json newContactJson:{method:'post', url:'/contact/new/json'}, // Edit the contact editContact:{method:'put', url:'/contact/edit'}, // Delete the contact delContact:{method:'delete', url:'/contact' } } export default CONTACT_APICopy the code

Note: This file is used to define different interface request information (including method and URL) and export it for use. When an interface is added or deleted, it only needs to be defined in this file.

Step 2: Create a new onesrc/service/http.jsfile

Import axios from 'axios' import service from './contactApi' import {Toast} from 'vant' // service loop to output different request method lets instance = axios.create({ baseURL: 'http://localhost:9000/api', timeout: 1000 }) const Http = { }; For (let key in service) {let API = service[key]; Http[key] = async function(params, // request parameters get: URL, PUT, POST, patch (data), delete: url isFormData = false, Config = {} // config) {let newParams = {} // Content-type if (params &&) isFormData) { newParams = new FormData() for (let i in params) { newParams.append(i, Params [I])}} else {newParams = params} / / request the return value of the if (API method = = = 'put' | | API. The method = = = 'post' | | API. The method = = = 'patch') {try {response = await instance[api.method](api.url, newParams, config) } catch (err) { response = err } } else if (api.method === 'delete' || api.method === 'get') { config.params = newParams try { response = await instance[api.method](api.url, config) } catch (err) { response = err } } return response; / / returns the response value}} / / interceptor add / / request interceptor instance. The interceptors. Request. Use (config = > {/ / do something before initiating Toast. Loading ({mask: False, duration: 0, // forbidClick: true, // disable message: 'loading... '}) return config}, () => {// request error toast.clear () Toast() Request to try again later ')}) / / response interceptor instance. The interceptors. Response. Use (res = > {/ / request is successful Toast. The clear () return res. Data}, () => {toast.clear () Toast(' request error, request retry later ')}) export default HttpCopy the code

The specific steps are as follows:

First, we introduce the contactapi.js file with the alias defined as Service.

import service from './contactApi'
Copy the code

Define a new axios instance, manage the contactList against the contactList of the current function module, configure the baseURL base domain name, timeout request timeout time, and so on, to distinguish from other function modules.

let instance = axios.create({ 
    baseURL: 'http://localhost:9000/api',
    timeout: 1000
})
Copy the code

Define HTTP as the container for the request method and configure the corresponding parameters (that is, other information in the request method, such as headers, Content-Type, Token, and so on). Formdata and Application /json have different parameter configurations. Formdata objects need to be defined for form-data parameters. Details are as follows:

If (params &&isFormData) {newParams = new FormData() for (let I in) params) { newParams.append(i, params[i]) } } else { newParams = params }Copy the code

Tips: isFormData is defined as a Boolean variable, which is used to identify whether it isFormData.

Initiates a network request and exports the return value according to different request modes.

// let response = {}; / / request the return value of the if (API method = = = 'put' | | API. The method = = = 'post' | | API. The method = = = 'patch') {try {response = await instance[api.method](api.url, newParams, config) } catch (err) { response = err } } else if (api.method === 'delete' || api.method === 'get') { config.params = newParams try { response = await instance[api.method](api.url, config) } catch (err) { response = err } } return response; // Returns the response valueCopy the code

Note: The difference between methods is that the parameters of get and delete are configured in config instead of using params.

Set request interceptors and response interceptors

/ interceptor add / / request interceptor instance. The interceptors. Request. Use (config = > {/ / do something before initiating Toast. Loading ({mask: false, duration: 0, // always forbidClick: true, // disallow clicking message: 'loading... '}) return config}, () => {// request error toast.clear () Toast() Request to try again later ')}) / / response interceptor instance. The interceptors. Response. Use (res = > {/ / request is successful Toast. The clear () return res. Data}, () => {toast.clear () Toast(' request error, request retry later ')})Copy the code

Export the SRC /service/http.js file for import elsewhere.

export default Http
Copy the code

Step 3: Import in the entry filehttp.jsAnd mount tovueOn the prototype.

Prototype.$Http = HttpCopy the code

Step 4: Use wrapped requests in components

Async getList(){let res = await this.$http.getcontactList () this.list = res.data},Copy the code

Note: we need to combine async and await to use it correctly. The specific method of use is:

  1. Before the defined network request functionasyncLogo.
  2. When receiving data returned from a request, the value is increasedawaitLogo.
  3. Tip: In the above function, only theresThey won’t be executed until they get itthis.list = res.data;Corresponds to the correspondingthenTo avoid callback hell.
  4. When Axios submits a form request, it automatically sets the Content-Type, which does not work manually.

conclusion

During project development, we need to encapsulate the network request method, which can effectively reduce the difficulty of later code maintenance. It is suggested that developers split it according to different functional modules, so as to facilitate the positioning of later code problems. In addition, it can achieve low coupling of the code and avoid more duplicate code.

​​

Encapsulation and use of AXIos requests

Thought analysis

The encapsulation of axios requests is nothing more than code management, where we can use the decouple idea of processing the interfaces of different functional modules into different modules and encapsulating a method dedicated to data interaction.

Step 1: Create a new onesrc/service/contactApi.jsfile

Const CONTACT_API = {getContactList:{method:'get', url:'/contactList'}, Form-data newContactForm:{method:'post', url:'/contact/new/form'}, Application /json newContactJson:{method:'post', url:'/contact/new/json'}, // Edit the contact editContact:{method:'put', url:'/contact/edit'}, // Delete the contact delContact:{method:'delete', url:'/contact' } } export default CONTACT_APICopy the code

Note: This file is used to define different interface request information (including method and URL) and export it for use. When an interface is added or deleted, it only needs to be defined in this file.

Step 2: Create a new onesrc/service/http.jsfile

Import axios from 'axios' import service from './contactApi' import {Toast} from 'vant' // service loop to output different request method lets instance = axios.create({ baseURL: 'http://localhost:9000/api', timeout: 1000 }) const Http = { }; For (let key in service) {let API = service[key]; Http[key] = async function(params, // request parameters get: URL, PUT, POST, patch (data), delete: url isFormData = false, Config = {} // config) {let newParams = {} // Content-type if (params &&) isFormData) { newParams = new FormData() for (let i in params) { newParams.append(i, Params [I])}} else {newParams = params} / / request the return value of the if (API method = = = 'put' | | API. The method = = = 'post' | | API. The method = = = 'patch') {try {response = await instance[api.method](api.url, newParams, config) } catch (err) { response = err } } else if (api.method === 'delete' || api.method === 'get') { config.params = newParams try { response = await instance[api.method](api.url, config) } catch (err) { response = err } } return response; / / returns the response value}} / / interceptor add / / request interceptor instance. The interceptors. Request. Use (config = > {/ / do something before initiating Toast. Loading ({mask: False, duration: 0, // forbidClick: true, // disable message: 'loading... '}) return config}, () => {// request error toast.clear () Toast() Request to try again later ')}) / / response interceptor instance. The interceptors. Response. Use (res = > {/ / request is successful Toast. The clear () return res. Data}, () => {toast.clear () Toast(' request error, request retry later ')}) export default HttpCopy the code

The specific steps are as follows:

First, we introduce the contactapi.js file with the alias defined as Service.

import service from './contactApi'
Copy the code

Define a new axios instance, manage the contactList against the contactList of the current function module, configure the baseURL base domain name, timeout request timeout time, and so on, to distinguish from other function modules.

let instance = axios.create({ 
    baseURL: 'http://localhost:9000/api',
    timeout: 1000
})
Copy the code

Define HTTP as the container for the request method and configure the corresponding parameters (that is, other information in the request method, such as headers, Content-Type, Token, and so on). Formdata and Application /json have different parameter configurations. Formdata objects need to be defined for form-data parameters. Details are as follows:

If (params &&isFormData) {newParams = new FormData() for (let I in) params) { newParams.append(i, params[i]) } } else { newParams = params }Copy the code

Tips: isFormData is defined as a Boolean variable, which is used to identify whether it isFormData.

Initiates a network request and exports the return value according to different request modes.

// let response = {}; / / request the return value of the if (API method = = = 'put' | | API. The method = = = 'post' | | API. The method = = = 'patch') {try {response = await instance[api.method](api.url, newParams, config) } catch (err) { response = err } } else if (api.method === 'delete' || api.method === 'get') { config.params = newParams try { response = await instance[api.method](api.url, config) } catch (err) { response = err } } return response; // Returns the response valueCopy the code

Note: The difference between methods is that the parameters of get and delete are configured in config instead of using params.

Set request interceptors and response interceptors

/ interceptor add / / request interceptor instance. The interceptors. Request. Use (config = > {/ / do something before initiating Toast. Loading ({mask: false, duration: 0, // always forbidClick: true, // disallow clicking message: 'loading... '}) return config}, () => {// request error toast.clear () Toast() Request to try again later ')}) / / response interceptor instance. The interceptors. Response. Use (res = > {/ / request is successful Toast. The clear () return res. Data}, () => {toast.clear () Toast(' request error, request retry later ')})Copy the code

Export the SRC /service/http.js file for import elsewhere.

export default Http
Copy the code

Step 3: Import in the entry filehttp.jsAnd mount tovueOn the prototype.

Prototype.$Http = HttpCopy the code

Step 4: Use wrapped requests in components

Async getList(){let res = await this.$http.getcontactList () this.list = res.data},Copy the code

Note: we need to combine async and await to use it correctly. The specific method of use is:

  1. Before the defined network request functionasyncLogo.
  2. When receiving data returned from a request, the value is increasedawaitLogo.
  3. Tip: In the above function, only theresThey won’t be executed until they get itthis.list = res.data;Corresponds to the correspondingthenTo avoid callback hell.
  4. When Axios submits a form request, it automatically sets the Content-Type, which does not work manually.

conclusion

During project development, we need to encapsulate the network request method, which can effectively reduce the difficulty of later code maintenance. It is suggested that developers split it according to different functional modules, so as to facilitate the positioning of later code problems. In addition, it can achieve low coupling of the code and avoid more duplicate code.

Encapsulation and use of AXIos requests

Thought analysis

The encapsulation of axios requests is nothing more than code management, where we can use the decouple idea of processing the interfaces of different functional modules into different modules and encapsulating a method dedicated to data interaction.

Step 1: Create a new onesrc/service/contactApi.jsfile

Const CONTACT_API = {getContactList:{method:'get', url:'/contactList'}, Form-data newContactForm:{method:'post', url:'/contact/new/form'}, Application /json newContactJson:{method:'post', url:'/contact/new/json'}, // Edit the contact editContact:{method:'put', url:'/contact/edit'}, // Delete the contact delContact:{method:'delete', url:'/contact' } } export default CONTACT_APICopy the code

Note: This file is used to define different interface request information (including method and URL) and export it for use. When an interface is added or deleted, it only needs to be defined in this file.

Step 2: Create a new onesrc/service/http.jsfile

Import axios from 'axios' import service from './contactApi' import {Toast} from 'vant' // service loop to output different request method lets instance = axios.create({ baseURL: 'http://localhost:9000/api', timeout: 1000 }) const Http = { }; For (let key in service) {let API = service[key]; Http[key] = async function(params, // request parameters get: URL, PUT, POST, patch (data), delete: url isFormData = false, Config = {} // config) {let newParams = {} // Content-type if (params &&) isFormData) { newParams = new FormData() for (let i in params) { newParams.append(i, Params [I])}} else {newParams = params} / / request the return value of the if (API method = = = 'put' | | API. The method = = = 'post' | | API. The method = = = 'patch') {try {response = await instance[api.method](api.url, newParams, config) } catch (err) { response = err } } else if (api.method === 'delete' || api.method === 'get') { config.params = newParams try { response = await instance[api.method](api.url, config) } catch (err) { response = err } } return response; / / returns the response value}} / / interceptor add / / request interceptor instance. The interceptors. Request. Use (config = > {/ / do something before initiating Toast. Loading ({mask: False, duration: 0, // forbidClick: true, // disable message: 'loading... '}) return config}, () => {// request error toast.clear () Toast() Request to try again later ')}) / / response interceptor instance. The interceptors. Response. Use (res = > {/ / request is successful Toast. The clear () return res. Data}, () => {toast.clear () Toast(' request error, request retry later ')}) export default HttpCopy the code

The specific steps are as follows:

First, we introduce the contactapi.js file with the alias defined as Service.

import service from './contactApi'
Copy the code

Define a new axios instance, manage the contactList against the contactList of the current function module, configure the baseURL base domain name, timeout request timeout time, and so on, to distinguish from other function modules.

let instance = axios.create({ 
    baseURL: 'http://localhost:9000/api',
    timeout: 1000
})
Copy the code

Define HTTP as the container for the request method and configure the corresponding parameters (that is, other information in the request method, such as headers, Content-Type, Token, and so on). Formdata and Application /json have different parameter configurations. Formdata objects need to be defined for form-data parameters. Details are as follows:

If (params &&isFormData) {newParams = new FormData() for (let I in) params) { newParams.append(i, params[i]) } } else { newParams = params }Copy the code

Tips: isFormData is defined as a Boolean variable, which is used to identify whether it isFormData.

Initiates a network request and exports the return value according to different request modes.

// let response = {}; / / request the return value of the if (API method = = = 'put' | | API. The method = = = 'post' | | API. The method = = = 'patch') {try {response = await instance[api.method](api.url, newParams, config) } catch (err) { response = err } } else if (api.method === 'delete' || api.method === 'get') { config.params = newParams try { response = await instance[api.method](api.url, config) } catch (err) { response = err } } return response; // Returns the response valueCopy the code

Note: The difference between methods is that the parameters of get and delete are configured in config instead of using params.

Set request interceptors and response interceptors

/ interceptor add / / request interceptor instance. The interceptors. Request. Use (config = > {/ / do something before initiating Toast. Loading ({mask: false, duration: 0, // always forbidClick: true, // disallow clicking message: 'loading... '}) return config}, () => {// request error toast.clear () Toast() Request to try again later ')}) / / response interceptor instance. The interceptors. Response. Use (res = > {/ / request is successful Toast. The clear () return res. Data}, () => {toast.clear () Toast(' request error, request retry later ')})Copy the code

Export the SRC /service/http.js file for import elsewhere.

export default Http
Copy the code

Step 3: Import in the entry filehttp.jsAnd mount tovueOn the prototype.

Prototype.$Http = HttpCopy the code

Step 4: Use wrapped requests in components

Async getList(){let res = await this.$http.getcontactList () this.list = res.data},Copy the code

Note: we need to combine async and await to use it correctly. The specific method of use is:

  1. Before the defined network request functionasyncLogo.
  2. When receiving data returned from a request, the value is increasedawaitLogo.
  3. Tip: In the above function, only theresThey won’t be executed until they get itthis.list = res.data;Corresponds to the correspondingthenTo avoid callback hell.
  4. When Axios submits a form request, it automatically sets the Content-Type, which does not work manually.

conclusion

During project development, we need to encapsulate the network request method, which can effectively reduce the difficulty of later code maintenance. It is suggested that developers split it according to different functional modules, so as to facilitate the positioning of later code problems. In addition, it can achieve low coupling of the code and avoid more duplicate code.