Go through axios completely and never be afraid to write requests again

Keywords: Javascript Front-end Vue

axios request method

It mainly includes get, post, put, patch and delete

get
get data

post
Submit data (form submission + file upload)

put
Update data (push all data to the server)

patch
Update data (only the modified data is pushed to the back end)

delete
Delete data

get method

Writing method
Call type

 axios.get('/data.json').then((res)=>{
      console.log(res)
    })

Copy code
Axios type

axios({
  method:'get',
  url:'/data.json'
}).then((res)=>{
     console.log(res)
})

params

Call type

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

axios() method type

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

post method

Call type

axios.post('/post',{},config)

The post method has three parameters: url, data and config. The config parameter is not discussed for the time being.
Generally, there are two types of uploaded data

Form data form submission (image upload, file upload)
application/json
After the request is initiated, you can enter the browser network to view the content type in the request header

Suppose we want to upload a data now:
let data = { id:12 }
Then we can pass it in directly:

axios.post('/post',data).then((res)=>{
  console.log(res)
})

axios() method type

axios({
  method:'post',
  url:'/post',
  data:data
}).then(...)

Small details of two kinds of data
When we upload a general let data = {ID: 12} data, the Network request header will be displayed as: application/json; charset=UTF-8
When we upload:

let data = {id:12}
let formData = new FormData()
for(let key in data){
      formData.append(key,data[key])
    }

Here, data is converted to format, and the format is changed to formdata.
Then the Network request header will be displayed as: multipart / form data; boundary=----WebKitFormBoundarywWFnSlPye1ZF8CSw
put method and patch method
The form is roughly the same as the post method, and the Network display is only different from the Request Method.

delete method

Writing method
url deletion method
//Delete directly from the url

axios.delete('/data.json',{
      params:{
        id:12
      }
    }).then((res)=>{
      console.log(res)
    })

Delete from the url, and the last part of the Network request header will be displayed as Query String Parameters
Request body deletion method

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

Delete from the request body, and the last part of the Network request header will be displayed as: Request Payload
The deletion methods of the two methods are different, and the specific use needs to be communicated with the back-end.

Concurrent request

brief introduction
Multiple requests are made at the same time and the return value is processed uniformly.
Case: suppose there is a chat tool with your chat records and personal information. At this time, two interfaces need to be called to request data. At this time, their return values need to be processed uniformly.
Methods provided by axios: all, spread
The axios.all method accepts an array as a parameter. Each element in the array is a request and returns a promise object. When all requests in the array have been completed, the then method is executed.
The axios.spread method is executed in the then method. This method takes a function as a parameter and returns a new function. The parameter of the received parameter function is the response returned by each request in the axios.all method.

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread((acct, perms) => {
    // After both requests are completed, acct is the return value of getUserAccount. Similarly, perms is the return value of getUserPermissions
  }));

Introduction to axios example

Why use instances?
When we need to use different back-end domain names, it is not convenient to call axios.get directly. We can call it by creating an instance. Different domain names correspond to different instances one by one.

Form of expression

 created() {
     let instance = axios.create({
       baseURL:'http://localhost:8080 ', / / basic request path
       timeout:1000,//Timeout setting
     })
     instance.get('/data.json').then(res=>{
        console.log(res)
     })
   }

Basic configuration method

 baseURL:'http://localhost:8080 ', / / requested domain name and basic address
   timeout:1000,//Request timeout length (ms)
   url:'/data.json',//Request path
   method:'get,post,put,patch,delete',//Request method
   headers:{
     token:''//Represents the identity information of the current login person
   },//Set request header
   params:{},//Splicing the request parameters on the url is an object
   data:{}//Putting the request parameter in the request body is an object

params and data are represented as objects.
The usage scenario is usually to transmit parameters in parallel when a request is initiated:
//Take the get request as an example. Get has two configurations: relative path and config

 axios.get('/data.json',{
  params:{
     //parameter
  }
 })

Parameter configuration method

1. Global configuration

axios.defaults. Basic configuration methods (baseurl, etc.)
For example:

 axios.defaults.timeout = 1000 //Global configuration request duration 1s

2. Instance configuration

 let instance = axios.create(
   //Basic configuration method
 )

If the global configuration method is set but the corresponding method is not set in the instance configuration, the global method shall be used. Otherwise, the method in the instance shall prevail.

3.axios request configuration

Depending on the specific situation, if the file calling a path is huge, we can set its request duration separately:

 instance.get('/data.json',{
   timeout:5000
 })

summary

Priority: request configuration > instance configuration > global configuration

Interceptor

Do some processing before initiating the request, and then do some processing after initiating the request.
It is divided into request interceptor and response interceptor

request interceptor

 axios.interceptors.request.use(
   config=>{
     //What to do before sending a request
     return config
   },
   err=>{
     // What to do when the request is wrong (error here, the request is not to the back end)
     return Promise.reject(err)//A promise object is returned here
   }
 )

Response interceptor

axios.interceptors.responce.use(
   res=>{
      //The request successfully processed the response data
      return res
   },err=>{
      //What to do in response to the error (error here, returned after reaching the backend)
      return Promise.reject(err)
   }
 )

Both of them return the promise object after responding to the error. What is the specific function?

 axios.get().then().catch(err=>{})

This code is the standard form when we usually send a get request. then will perform the operation after the request is successful, and catch is used to catch errors.
After we intercept the response, the promise returned by the err of both the request and the response interceptor will enter the catch.

Cancel interceptor (just understand)

 let inerceptors = axios.interceptors.request.use
 (config=>{
      config.header = {
          auth:true
      }
      return config
 })
 axios.inerceptors.request.eject(interceptors) //Use the axios global to call interceptors, which cancels the interception...

Take a chestnut

Control login status through interceptor

 // Login status, with token
 let request = axios.create({})
 request.interceptors.request.use
 (config => {
    config.headers.token = ''
    return config
 })
 // Non login status, no token 
 let request2 = axios.create({})

With a token, you can access more data and get more data. Without a token, you can't. Similar to comments, you need to log in

error handling

Form of expression

//First set the interceptor
 axios.interceptors.request.use(
  config =>{
    return config
  },err =>{
    return Promise.reject(err)
  }
 )
 axios.interceptors.response.use(
  res =>{
    return res
  },err =>{
    return Promise.reject(err)
  }
 )
 ​
 //Wrong acquisition
 axios.get('/data.json').then(res=>{
   console.log(res)
 }).catch(err =>{
   console.log(err) //All error handling goes here
 })

In the specific practice process, we need to create a unified error handling, and put all error types in the interception, which is convenient for us to use when calling the interface later.

Chestnuts

 //Create a request instance
 let instance = axios.create({})
 //Add a request interceptor for the request instance
 instance.interceptors.request.use(
  config =>{
    return config
  },err =>{
  //Request error: generally, the http status code starts with 4. Common errors are 401 timeout and 404 not found. Most of them are front-end browser errors
     return Promise.reject(err)
  }
 )
 instance.interceptors.response.use(
   res=>{
     return res
   },err =>{
     //Response error: generally, the http status code starts with 5, 500 system error, 502 system restart, etc., which is biased towards the error returned by the server
     return Promise.reject(err)
   }
 )
 ​
 //use
 instance.get('data').then(res=>{
    console.log(res)
 }).catch(err =>{
     console.log(err)
 })

Cancel request
It is used to cancel an ongoing http request. It is rarely used, so I won't introduce it

Author: Benjamin 59
Link: https://juejin.cn/post/7034827130701611016
Source: rare earth Nuggets
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, and for non-commercial reprint, please indicate the source.

Posted by ppera on Tue, 30 Nov 2021 19:32:12 -0800