Talk about the unknown secrets in Axios! Understand Axios in one article

Front end paper aircraft 2021-10-14 06:28:11

 Axios Introduce

1、Axios What is it? ?

Axios It's based on promise Of HTTP library , Be similar to jQuery Of ajax, be used for http request . It can be applied to browser and node.js, Can be used for both clients , It can also be used for node.js Write the server side .

2、Axios characteristic

(1) Support Promise API

(2) Intercept requests and responses , such as : Do something before adding authorization and response to the request .

(3) Transform request data and response data , such as : Perform request encryption or response data encryption .

(4) Cancel the request

(5) Automatic conversion JSON data

(6) The client supports defense XSRF

3、 Browser support

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


Axios Basic use

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

Open the console and take a look , There's already data  

axios Is it used successfully


Axios Common request methods

Method list :get, post, put, patch, delete etc. .

  • get: General users get data
  • post: It is generally used for form submission and file upload
  • patch: Update data ( Only push the modified data to the back end )
  • put: Update data ( Push all data to the server )
  • delete: Delete data

remarks :post It is generally used to create new data ,put Generally used to update data ,patch It is generally used for data updating when there is a large amount of data .

1、get Method

Mode one

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

Mode two

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

With parameters get The request is actually http://xxxxx/data.json?id=12, After writing so much, the result is url Added parameters .

Introduction to browser console :

  1. Request URL: request URL
  2. Request Method: Request mode

2、post Method

post There are two common data request formats :

1.form-data( Often used for form submission ( Image upload 、 Upload files ))

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')
})

Be careful : Request address Request URL: http://xxxxxxx/data.json,

Request header Content-Type: multipart/form-data; boundary=——WebKitFormBoundarydgohzXGsZdFwS16Y

Parameter form :id:12

2.application/json( Commonly used )

Mode one

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

Mode two

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

Be careful : Request address Request URL: http://xxxxxxxx/data.json,

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

Parameter form :{ id:12 }

3、put Method

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

4、patch Method

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

5、delete Method

Mode one :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)
})

Mode two :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)
})

Be careful :params The method will splice the request parameters in URL above ,Request URL: http://xxxxxxxx/data.json?id=12

Parameter form :id:12

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

data The method does not talk about parameter splicing , Is placed directly in the request body ,Request URL: http://xxxxxxxx/data.json

Parameter form :{id:12}

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

summary : The above methods correspond to two writing methods :(1) Use the alias : Form like axios.get();(2) Do not use aliases such as axios();

6、 Concurrent request

Concurrent request , Is to make multiple requests at the same time , And handle the return value in a unified way . similar promise.all.

In the following example , We use axios.all, Yes data.json/city.json Request at the same time , Use axios.spread, Process the returned results separately . The code is as follows :

// Concurrent request
axios.all([axios.get("/data.json"), axios.get("/city.json")]).then(
axios.spread((dataRes, cityRes) => {
console.log(dataRes, cityRes);
})
);

Be careful :axios.all The parameter of is the array of the request function , In the corresponding callback then in , call axios.spead Process the return value , that will do .

Application scenarios of concurrent requests : Multiple requests need to be made at the same time , And when you need to process the return value of the interface call at the same time , We can use concurrent requests .


Axio example

1、axios Instance creation

such as : There are multiple back-end interface addresses (www.test.com、www.example.com), And the timeout is different (1000ms、2000ms), This is the time , We can create instances .

Ideas as follows : Create multiple instances , Configure different timeout duration , Use different instances to request different interfaces . Use axios.acreate To create an instance , Configuration related information , Make a network request . The code is as follows :

// example 1
let instance = axios.create({
baseURL:'http://loacalhost:8080',
timeout:1000
})
instance.get('/data.json').then(res=>{
console.log(res)
})
// example 2
let instance2 = axios.create({
baseURL: "http://loacalhost:8081",
timeout: 2000
});
instance2.get("/city.json").then(res => {
console.log(res);
});

remarks : At this point, we can access http://loacalhost:8080 And http://loacalhost:8081 Interface of two different domain names , And use different configurations .

2、axios Instance configuration

(1) Configuration list

  • baseURL: Requested domain name ( Base address ).

  • timeout: The timeout of the request , After exceeding, the back end returns 401.

    remarks : It is generally defined by the back end , The processing time of the back-end interface is long , If the request takes too long , Back end processing can't come over , It will block , Put more pressure on the server . After setting , Can be released in time .

  • url: Request path .

  • method: Request method . Such as :get、post、put、patch、delete etc. .

  • headers: Request header .

  • params: Splice request parameters into url On

  • data: Put the request parameters into the request body  

axios.create({
baseURL:'', // Requested domain name ( Base address )
timeout:2000, // The timeout of the request , Unit millisecond , Default .
url:'/data.json', // Request path 
method:'get', // Request method 
headers:{
token:''
}, // Set request header 
params:{
},// Splice request parameters into url On 
data:{
}, // Put the request parameters into the request body 
});

(2) Three configurations

  • axios Global configuration
axios.defaults.baseURL = ‘http://localhost:8080axios.defaults.timeout = 2000
  •  axios The instance configuration
let instance = axios.create();
instance.defaults.timeout = 3000
  • axios Request configuration
instance.get(‘/data.json’,{
timeout:5000
})

priority :axios Global configuration < axios The instance configuration < axios Request configuration

3、 Usage of common parameter configuration

give an example 1:

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

analysis : The parameters configured are baseURL:‘http://localhost:9090’,timeout:1000,method:‘get’,params:{ id:10},url:’/contactList’

give an example 2:

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

analysis : The parameters configured are baseURL:‘http://localhost:9091’,timeout:5000,method:‘get’,url:’/contactList’

Be careful : The final effective configuration is covered by the high priority and the low priority .


Axios Interceptor 、 Error handling and cancellation request

1、 Interceptor

What is an interceptor ?

Intercept requests or responses before they are processed , Divided into two : Request interceptor and response interceptor .

How to use interceptors

Request interceptor

// Request interceptor 
axios.interceptors.request.use(config => {
// What to do before sending the request 
return config;
}, err=>{
// Logical processing when the request is wrong 
return Promise.reject(err)
});

Response interceptors

// Response interceptors 
axios.interceptors.response.use(res => {
// Data processing after successful request 
return res;
}, err=>{
// Logical processing in response to errors 
return Promise.reject(err)
});

Cancel the interceptor

let inter = axios.interceptors.request.use(config=>{
config.header={
auth:true
}
return config
})
axios.interceptors.request.eject(inter)

Practical examples A: Login rights

need token Interface instance of

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

Unwanted token Interface instance of

let newInstance = axios.create({ });

Practical examples B: Mobile development data loading loading Animation

// Requested load animation loading
let instance_phone = axios.create({ });
instance_phone.interceptors.request.use(config=>{
$('#loading').show();
return config
})
instance_phone.interceptors.response.use(res=>{
$('#loading').hide();
return res
})

remarks : The effect is to display when requesting data loading Animation , Hide after data response loading Animation .

2、 Error handling , Intercept

Combining a request interceptor with a response interceptor , Whether it's a request error or a response error , It will be carried out catch Method .

// Request interceptor 
axios.interceptors.request.use(
config => {
// What to do before sending the request 
return config;
},
err => {
// Logical processing when the request is wrong 
return Promise.reject(err);
}
);
// Response interceptors 
axios.interceptors.response.use(
res => {
// Data processing after successful request 
return res;
},
err => {
// Logical processing in response to errors 
return Promise.reject(err);
}
);
axios
.get("data.json")
.then(res => {
console.log(res);
})
.catch(err => {
console.log(res);
});

Examples of error handling

In actual development , Not every time the network requests , Use catch Method , You can add a unified error handling method . The code is as follows :

// Request error handling 
let instance = axios.create({ });
instance.interceptors.request.use(
config => {
return config;
},
err => {
// Common status codes for request errors :4XX 401- request timeout 404-mot found
$("#error").show();
setTimeout(()=>{
$("#error").hide();
}, 2000)
return Promise.reject(err);
}
);
// Response error handling 
instance.interceptors.response.use(
res => {
return res;
},
err => {
// Common status codes for response errors 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,' The request is successful ')
}).catch(err=>{
console.log(err,' Processing other than the processing set by the interceptor ')
})

Thought analysis : Create instance first , Set request interceptor and response interceptor for the instance .

  • (1) Common status codes for request errors are shown in 4 start , Such as 401- request timeout 、404- Interface not found ;
  • (2) Common status codes that respond to errors are shown in 5 start , Such as 500- Server error 、502- Server restart, etc .
  • (3) Handle the operation of setting request interceptor and response interceptor , If there are other operations , We can ask when , In the use of catch Method .

3、 Cancel the request ( Not commonly used ) 

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 ( Parameters msg)
source.cancel(' The custom string is optional ')

Application scenarios

When querying data , for ages (3-5s) Data not yet available , You need to cancel the request at this time .

 axios Encapsulation and use of requests

Thought analysis

axios  Requested encapsulation , Just to facilitate code management , We can use the idea of separation , The interfaces of different functional modules are processed into different modules , Then encapsulate a method , Designed for data interaction .

First step : newly build  src/service/contactApi.js  file

const CONTACT_API = {
// Get contact list 
getContactList:{
method:'get',
url:'/contactList'
},
// New contact form-data
newContactForm:{
method:'post',
url:'/contact/new/form'
},
// New contact application/json
newContactJson:{
method:'post',
url:'/contact/new/json'
},
// Edit Contact 
editContact:{
method:'put',
url:'/contact/edit'
},
// Delete Contact 
delContact:{
method:'delete',
url:'/contact'
}
}
export default CONTACT_API

remarks : This file has only one purpose , Define different interface request information ( contain  methodurl etc. ) Export and use . When an interface is added or deleted , Just define it in this file .

The second step : newly build  src/service/http.js  file

import axios from 'axios'
import service from './contactApi'
import { Toast } from 'vant'
// service Loop traversal outputs different request methods 
let instance = axios.create({
baseURL: 'http://localhost:9000/api',
timeout: 1000
})
const Http = { }; // Container for the package request method 
// Request format / Unification of parameters 
for (let key in service) {
let api = service[key]; // url method
// async effect : Avoid going to hell 
Http[key] = async function( params, // Request parameters get:url,put,post,patch(data),delete:url isFormData = false, // Is the identity form-data request  config = { } // Configuration parameters  ) {
let newParams = { }
// content-type Whether it is form-data The judgment of the 
if (params && isFormData) {
newParams = new FormData()
for (let i in params) {
newParams.append(i, params[i])
}
} else {
newParams = params
}
// Judgment of different requests 
let response = { }; // Requested return value 
if (api.method === 'put' || api.method === 'post' || api.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; // Return the response value 
}
}
// Add interceptor 
// Request interceptor 
instance.interceptors.request.use(config => {
// What to do before making a request 
Toast.loading({
mask: false,
duration: 0, // Always exist 
forbidClick: true, // No clicking 
message: ' Loading ...'
})
return config
}, () => {
// Request error 
Toast.clear()
Toast(' Request error , Request to try again later ')
})
// Response interceptors 
instance.interceptors.response.use(res => {
// The request is successful 
Toast.clear()
return res.data
}, () => {
Toast.clear()
Toast(' Request error , Request to try again later ')
})
export default Http

The specific ideas and steps are as follows :

First , We introduce contactApi.js file , The alias is defined as  service.

import service from './contactApi'

  Define a new  axios  example , Manage the contact list for the current function module  contactList , To configure baseURL Basic domain name 、timeout Request timeout, etc , Different from other functional modules .

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

Definition  http  As a container for request methods , Configure the corresponding parameters ( That is, other information in the request method , such as  headers,content-type,token wait ). It should be noted that , In which we have to distinguish  content-type There are two forms of :form-data  And  application/json, Their parameter configurations are different ,form-data  Parameters of form , We need to define  Formdata  object . As follows :

let newParams = { }
// content-type Whether it is form-data The judgment of the 
if (params && isFormData) {
newParams = new FormData()
for (let i in params) {
newParams.append(i, params[i])
}
} else {
newParams = params
}

reminder : among  isFormData  Defined as  Boolean  Variable , Used to identify whether it is  FormData  form .

According to different request methods , Initiate network request , And export the return value .

// Judgment of different requests 
let response = { }; // Requested return value 
if (api.method === 'put' || api.method === 'post' || api.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; // Return the response value 

Be careful : The difference between the different methods is :get  And  delete  Parameters in  config  Middle configuration , Instead of using  params .

Set request interceptor and response interceptor

/ Add interceptor
// Request interceptor 
instance.interceptors.request.use(config => {
// What to do before making a request 
Toast.loading({
mask: false,
duration: 0, // Always exist 
forbidClick: true, // No clicking 
message: ' Loading ...'
})
return config
}, () => {
// Request error 
Toast.clear()
Toast(' Request error , Request to try again later ')
})
// Response interceptors 
instance.interceptors.response.use(res => {
// The request is successful 
Toast.clear()
return res.data
}, () => {
Toast.clear()
Toast(' Request error , Request to try again later ')
})

  export src/service/http.js file , For introduction elsewhere .

export default Http

The third step : Import... In the entry file  http.js , And mount  vue  On the prototype .

import Http from './service/http'
// hold Http Mount to Vue For instance 
Vue.prototype.$Http = Http

Step four : Use encapsulated requests in components

// Get contact list 
async getList(){
let res = await this.$Http.getContactList()
this.list = res.data
},

Be careful : In use , We need to combine  async  And  await  In order to use . The specific method of use is :

  1. Add... Before the defined network request function  async  identification .
  2. When receiving the request to return data , increase  await  identification .
  3. Tips : In the above function , Only in  res  Only after you get it  this.list = res.data;  Equivalent to in the corresponding  then  Statement executed in , Avoiding a callback to hell .
  4. axios Automatically set when submitting a form request content-type, At this time, the manual setting is invalid .

summary

In the process of project development , We need to encapsulate the method of network request , It can effectively reduce the difficulty of later code maintenance , It is recommended that developers split according to different functional modules , Facilitate the positioning of later code problems . in addition , It can also realize low coupling of code , Avoid more duplicate code .

​​

 axios Encapsulation and use of requests

Thought analysis

axios  Requested encapsulation , Just to facilitate code management , We can use the idea of separation , The interfaces of different functional modules are processed into different modules , Then encapsulate a method , Designed for data interaction .

First step : newly build  src/service/contactApi.js  file

const CONTACT_API = {
// Get contact list 
getContactList:{
method:'get',
url:'/contactList'
},
// New contact form-data
newContactForm:{
method:'post',
url:'/contact/new/form'
},
// New contact application/json
newContactJson:{
method:'post',
url:'/contact/new/json'
},
// Edit Contact 
editContact:{
method:'put',
url:'/contact/edit'
},
// Delete Contact 
delContact:{
method:'delete',
url:'/contact'
}
}
export default CONTACT_API

remarks : This file has only one purpose , Define different interface request information ( contain  methodurl etc. ) Export and use . When an interface is added or deleted , Just define it in this file .

The second step : newly build  src/service/http.js  file

import axios from 'axios'
import service from './contactApi'
import { Toast } from 'vant'
// service Loop traversal outputs different request methods 
let instance = axios.create({
baseURL: 'http://localhost:9000/api',
timeout: 1000
})
const Http = { }; // Container for the package request method 
// Request format / Unification of parameters 
for (let key in service) {
let api = service[key]; // url method
// async effect : Avoid going to hell 
Http[key] = async function( params, // Request parameters get:url,put,post,patch(data),delete:url isFormData = false, // Is the identity form-data request  config = { } // Configuration parameters  ) {
let newParams = { }
// content-type Whether it is form-data The judgment of the 
if (params && isFormData) {
newParams = new FormData()
for (let i in params) {
newParams.append(i, params[i])
}
} else {
newParams = params
}
// Judgment of different requests 
let response = { }; // Requested return value 
if (api.method === 'put' || api.method === 'post' || api.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; // Return the response value 
}
}
// Add interceptor 
// Request interceptor 
instance.interceptors.request.use(config => {
// What to do before making a request 
Toast.loading({
mask: false,
duration: 0, // Always exist 
forbidClick: true, // No clicking 
message: ' Loading ...'
})
return config
}, () => {
// Request error 
Toast.clear()
Toast(' Request error , Request to try again later ')
})
// Response interceptors 
instance.interceptors.response.use(res => {
// The request is successful 
Toast.clear()
return res.data
}, () => {
Toast.clear()
Toast(' Request error , Request to try again later ')
})
export default Http

The specific ideas and steps are as follows :

First , We introduce contactApi.js file , The alias is defined as  service.

import service from './contactApi'

  Define a new  axios  example , Manage the contact list for the current function module  contactList , To configure baseURL Basic domain name 、timeout Request timeout, etc , Different from other functional modules .

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

Definition  http  As a container for request methods , Configure the corresponding parameters ( That is, other information in the request method , such as  headers,content-type,token wait ). It should be noted that , In which we have to distinguish  content-type There are two forms of :form-data  And  application/json, Their parameter configurations are different ,form-data  Parameters of form , We need to define  Formdata  object . As follows :

let newParams = { }
// content-type Whether it is form-data The judgment of the 
if (params && isFormData) {
newParams = new FormData()
for (let i in params) {
newParams.append(i, params[i])
}
} else {
newParams = params
}

reminder : among  isFormData  Defined as  Boolean  Variable , Used to identify whether it is  FormData  form .

According to different request methods , Initiate network request , And export the return value .

// Judgment of different requests 
let response = { }; // Requested return value 
if (api.method === 'put' || api.method === 'post' || api.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; // Return the response value 

Be careful : The difference between the different methods is :get  And  delete  Parameters in  config  Middle configuration , Instead of using  params .

Set request interceptor and response interceptor

/ Add interceptor
// Request interceptor 
instance.interceptors.request.use(config => {
// What to do before making a request 
Toast.loading({
mask: false,
duration: 0, // Always exist 
forbidClick: true, // No clicking 
message: ' Loading ...'
})
return config
}, () => {
// Request error 
Toast.clear()
Toast(' Request error , Request to try again later ')
})
// Response interceptors 
instance.interceptors.response.use(res => {
// The request is successful 
Toast.clear()
return res.data
}, () => {
Toast.clear()
Toast(' Request error , Request to try again later ')
})

  export src/service/http.js file , For introduction elsewhere .

export default Http

The third step : Import... In the entry file  http.js , And mount  vue  On the prototype .

import Http from './service/http'
// hold Http Mount to Vue For instance 
Vue.prototype.$Http = Http

Step four : Use encapsulated requests in components

// Get contact list 
async getList(){
let res = await this.$Http.getContactList()
this.list = res.data
},

Be careful : In use , We need to combine  async  And  await  In order to use . The specific method of use is :

  1. Add... Before the defined network request function  async  identification .
  2. When receiving the request to return data , increase  await  identification .
  3. Tips : In the above function , Only in  res  Only after you get it  this.list = res.data;  Equivalent to in the corresponding  then  Statement executed in , Avoiding a callback to hell .
  4. axios Automatically set when submitting a form request content-type, At this time, the manual setting is invalid .

summary

In the process of project development , We need to encapsulate the method of network request , It can effectively reduce the difficulty of later code maintenance , It is recommended that developers split according to different functional modules , Facilitate the positioning of later code problems . in addition , It can also realize low coupling of code , Avoid more duplicate code .

 axios Encapsulation and use of requests

Thought analysis

axios  Requested encapsulation , Just to facilitate code management , We can use the idea of separation , The interfaces of different functional modules are processed into different modules , Then encapsulate a method , Designed for data interaction .

First step : newly build  src/service/contactApi.js  file

const CONTACT_API = {
// Get contact list 
getContactList:{
method:'get',
url:'/contactList'
},
// New contact form-data
newContactForm:{
method:'post',
url:'/contact/new/form'
},
// New contact application/json
newContactJson:{
method:'post',
url:'/contact/new/json'
},
// Edit Contact 
editContact:{
method:'put',
url:'/contact/edit'
},
// Delete Contact 
delContact:{
method:'delete',
url:'/contact'
}
}
export default CONTACT_API

remarks : This file has only one purpose , Define different interface request information ( contain  methodurl etc. ) Export and use . When an interface is added or deleted , Just define it in this file .

The second step : newly build  src/service/http.js  file

import axios from 'axios'
import service from './contactApi'
import { Toast } from 'vant'
// service Loop traversal outputs different request methods 
let instance = axios.create({
baseURL: 'http://localhost:9000/api',
timeout: 1000
})
const Http = { }; // Container for the package request method 
// Request format / Unification of parameters 
for (let key in service) {
let api = service[key]; // url method
// async effect : Avoid going to hell 
Http[key] = async function( params, // Request parameters get:url,put,post,patch(data),delete:url isFormData = false, // Is the identity form-data request  config = { } // Configuration parameters  ) {
let newParams = { }
// content-type Whether it is form-data The judgment of the 
if (params && isFormData) {
newParams = new FormData()
for (let i in params) {
newParams.append(i, params[i])
}
} else {
newParams = params
}
// Judgment of different requests 
let response = { }; // Requested return value 
if (api.method === 'put' || api.method === 'post' || api.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; // Return the response value 
}
}
// Add interceptor 
// Request interceptor 
instance.interceptors.request.use(config => {
// What to do before making a request 
Toast.loading({
mask: false,
duration: 0, // Always exist 
forbidClick: true, // No clicking 
message: ' Loading ...'
})
return config
}, () => {
// Request error 
Toast.clear()
Toast(' Request error , Request to try again later ')
})
// Response interceptors 
instance.interceptors.response.use(res => {
// The request is successful 
Toast.clear()
return res.data
}, () => {
Toast.clear()
Toast(' Request error , Request to try again later ')
})
export default Http

The specific ideas and steps are as follows :

  First , We introduce contactApi.js file , The alias is defined as  service.

import service from './contactApi'

  Define a new  axios  example , Manage the contact list for the current function module  contactList , To configure baseURL Basic domain name 、timeout Request timeout, etc , Different from other functional modules .

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

Definition  http  As a container for request methods , Configure the corresponding parameters ( That is, other information in the request method , such as  headers,content-type,token wait ). It should be noted that , In which we have to distinguish  content-type There are two forms of :form-data  And  application/json, Their parameter configurations are different ,form-data  Parameters of form , We need to define  Formdata  object . As follows :

let newParams = { }
// content-type Whether it is form-data The judgment of the 
if (params && isFormData) {
newParams = new FormData()
for (let i in params) {
newParams.append(i, params[i])
}
} else {
newParams = params
}

reminder : among  isFormData  Defined as  Boolean  Variable , Used to identify whether it is  FormData  form .

According to different request methods , Initiate network request , And export the return value .

// Judgment of different requests 
let response = { }; // Requested return value 
if (api.method === 'put' || api.method === 'post' || api.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; // Return the response value 

Be careful : The difference between the different methods is :get  And  delete  Parameters in  config  Middle configuration , Instead of using  params .

Set request interceptor and response interceptor

/ Add interceptor
// Request interceptor 
instance.interceptors.request.use(config => {
// What to do before making a request 
Toast.loading({
mask: false,
duration: 0, // Always exist 
forbidClick: true, // No clicking 
message: ' Loading ...'
})
return config
}, () => {
// Request error 
Toast.clear()
Toast(' Request error , Request to try again later ')
})
// Response interceptors 
instance.interceptors.response.use(res => {
// The request is successful 
Toast.clear()
return res.data
}, () => {
Toast.clear()
Toast(' Request error , Request to try again later ')
})

  export src/service/http.js file , For introduction elsewhere .

export default Http

The third step : Import... In the entry file  http.js , And mount  vue  On the prototype .

import Http from './service/http'
// hold Http Mount to Vue For instance 
Vue.prototype.$Http = Http

Step four : Use encapsulated requests in components

// Get contact list 
async getList(){
let res = await this.$Http.getContactList()
this.list = res.data
},

Be careful : In use , We need to combine  async  And  await  In order to use . The specific method of use is :

  1. Add... Before the defined network request function  async  identification .
  2. When receiving the request to return data , increase  await  identification .
  3. Tips : In the above function , Only in  res  Only after you get it  this.list = res.data;  Equivalent to in the corresponding  then  Statement executed in , Avoiding a callback to hell .
  4. axios Automatically set when submitting a form request content-type, At this time, the manual setting is invalid .

summary

In the process of project development , We need to encapsulate the method of network request , It can effectively reduce the difficulty of later code maintenance , It is recommended that developers split according to different functional modules , Facilitate the positioning of later code problems . in addition , It can also realize low coupling of code , Avoid more duplicate code .

Please bring the original link to reprint ,thank
Similar articles

2021-10-14

2021-10-14

2021-10-14

2021-10-14

2021-10-14

2021-10-14

2021-10-14

2021-10-14

2021-10-14

2021-10-14

2021-10-14