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

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)

  • dlelete

    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)
})
Copy code

params

If we need to load: http://localhost:8080/data.json?id=12 , how to get it?

Call type

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

axios() method type

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

post method

Writing method

Call type

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

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)
})
Copy code

axios() method type

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

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])
    }
Copy code

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)
    })
Copy code

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)
    })
Copy code

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
  }));
Copy code

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)
     })
   }
Copy code

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
Copy code

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
  }
 })
Copy code

Parameter configuration method

1. Global configuration

 axios.defaults.Basic configuration method( baseurl Etc.)
 For example:
 axios.defaults.timeout = 1000 //Global configuration request duration 1s
Copy code

2. Instance configuration

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

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
 })
Copy code

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
   }
 )
Copy code

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)
   }
 )
Copy code

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

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

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...
Copy code

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({})
Copy code

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
 })
Copy code

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)
 })
Copy code

Cancel request

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

last

If you think this article is a little helpful to you, give it a compliment. Or you can join my development exchange group: 1025263163 learn from each other, and we will have professional technical Q & A to solve doubts

If you think this article is useful to you, please click star: http://github.crmeb.net/u/defu esteem it a favor  !

Tags: axios github .NET crmeb

Posted on Wed, 01 Dec 2021 07:25:42 -0500 by gamerzfuse