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

Front end paper aircraft 2021-10-14 06:28:11
talk unknown secrets axios understand


 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 .

版权声明
本文为[Front end paper aircraft]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/10/20211002145418019i.html

  1. Html + CSS + JS implémentation ️ Responsive Lucky Turnover ️ [with full source Sharing]
  2. Ren Jialun, who married young, was in a mess. Now she feels that it is a blessing in disguise
  3. 达梦数据库使用disql生成html格式的巡检报告
  4. React render phase parsing II - beginwork process
  5. Tableau linéaire de la structure des données (dessin à la main)
  6. In 2022, what are the highlights and popular elements in skirts to make skirts more elegant and gentle?
  7. JQuery installation
  8. Exemple de développement Android, dernière compilation de questions d'entrevue Android
  9. Differences and relations between JDK, JRE and JVM, nginx architecture diagram
  10. 【Azure 云服务】Azure Cloud Service 为 Web Role(IIS Host)增加自定义字段 (把HTTP Request Header中的User-Agent字段增加到IIS输出日志中)
  11. 【Azure 云服务】Azure Cloud Service 为 Web Role(IIS Host)增加自定义字段 (把HTTP Request Header中的User-Agent字段增加到IIS输出日志中)
  12. Questions d'entrevue pour les ingénieurs en développement Android, Android Foundation 72 questions
  13. It's kind of Cadillac CT6 to have a Mercedes Benz S-class captain and a 10At entry-level configuration, falling to less than 300000
  14. H6 meets the strong enemy again! The car body has a Cayenne visual sense, breaking 8.8 seconds, and the top configuration is less than 130000
  15. How nginx supports HTTPS and Linux kernel video tutorial
  16. Le martyr se réjouit de sa vieillesse Audi R8 V10 performance Rwd
  17. import 方式隨意互轉,感受 babel 插件的威力
  18. Le mode d'importation peut se déplacer librement pour sentir la puissance du plug - in Babel
  19. Pas de héros en termes de ventes!Du point de vue de la force du produit, la nouvelle version ax7 Mach est plus forte que H6
  20. The vue3 + TS project introduces vant as needed
  21. 深入浅出虚拟 DOM 和 Diff 算法,及 Vue2 与 Vue3 中的区别
  22. 深入淺出虛擬 DOM 和 Diff 算法,及 Vue2 與 Vue3 中的區別
  23. Explorer les algorithmes DOM et diff virtuels et les différences entre vue2 et vue3
  24. 两万字Vue基础知识总结,小白零基础入门,跟着路线走,不迷路(建议收藏)
  25. Résumé des connaissances de base de 20 000 mots vue, Introduction à la petite base blanche zéro, suivre la route et ne pas se perdre (Collection recommandée)
  26. 兩萬字Vue基礎知識總結,小白零基礎入門,跟著路線走,不迷路(建議收藏)
  27. "Talk show conference 4" Zhou qimo a remporté le championnat. Tout le monde l'admire. Il est mature et stable et a une vue d'ensemble
  28. Test logiciel entrevue non technique questions classiques - mise à jour continue!
  29. Digital forward disassembly reverse disassembly
  30. Analyse du cache distribué redis et essence de l'entrevue en usine v6.2.6
  31. [Hadoop 3. X series] use of HDFS rest HTTP API (II) httpfs
  32. Zhang Daxian sang in the morning to bless the motherland, xYG team: singing is much better than us
  33. My three years' experience -- avoiding endless internal friction
  34. Introduction à l'algorithme "dénombrement binaire" modéré 01 - - question d'entrevue leetcode 10.09. Recherche de matrice de tri
  35. Introduction à l'algorithme simple 06 - - leetcode 34. Trouver la première et la dernière position d'un élément dans un tableau de tri
  36. CSS animation
  37. Explain the new tags in HTML5 and the pseudo classes and pseudo elements in CSS3
  38. They are all talking about "serverless first", but do you really understand serverless?
  39. [apprentissage de l'algorithme] 1486. Fonctionnement exclusif du tableau (Java / C / C + + / python / go / Rust)
  40. Front and back end data interaction (VI) -- advantages, disadvantages and comparison of Ajax, fetch and Axios
  41. Front and back end data interaction (V) -- what is Axios?
  42. Front and back end data interaction (III) -- Ajax encapsulation and call
  43. 前端 100 万行代码是怎样的体验?
  44. 湖中剑 前端周刊 #10(ESLint8、Web 端侧 AI、react-if)
  45. 湖中劍 前端周刊 #10(ESLint8、Web 端側 AI、react-if)
  46. 前端 100 萬行代碼是怎樣的體驗?
  47. Huzhong Sword Front End Weekly # 10 (eslint8, Web end ai, React if)
  48. Quelle est l'expérience du premier million de lignes de code?
  49. Pancakeswap front-end source compilation and deployment Linux
  50. Pancakeswap front-end source compilation - Windows
  51. Walls and columns are powered, and 50W transmission power is available in any corner. The University of Tokyo has built a wireless charging house
  52. Pas besoin d'embrayage pour allumer une voiture?Vieux conducteur: la voiture est très blessée par des erreurs. Ces mauvaises habitudes doivent être changées!
  53. Cadre de développement Android MVP, résumé de l'entrevue
  54. [Azure Cloud Service] Azure Cloud Service ajoute des champs personnalisés pour le rôle Web (hôte IIS) (ajoute le champ user agent dans l'en - tête de demande http au Journal de sortie IIS)
  55. Principes de la plate - forme de développement Android, questions d'entrevue de développement Android
  56. [Azure Cloud Service] Azure Cloud Service ajoute des champs personnalisés pour le rôle Web (hôte IIS) (ajoute le champ user agent dans l'en - tête de demande http au Journal de sortie IIS)
  57. Weilai es8 was listed in Norway and SAIC's driverless concept car appeared at the World Expo
  58. One of the most high-frequency algorithm problems in the front end! Reverse linked list
  59. Échange de doigts d'épée 11. Nombre minimum de tableaux rotatifs
  60. Questions et réponses à l'entrevue Big Data (réimprimé)