current position:Home>Axios usage

Axios usage

2022-06-24 08:20:22Bean paste,

One , Preface

1.axios Is based on promise Of http library

2. You can use the package management tool to install :npm install axios

Two , Use axios Three ways to send a request

(1) To configure config

import axios from "axios"
axios({
    
	url:'xxx', // request url, Required 
	method:'get | post | ...', // Request method , Default get
	headers:{
    token:'xxxx'} // Request header 
	params: {
     //get Request to pass parameters 
    	ID: 12345
  	},
})

(2) Use the alias

import axios from "axios"

// After using the alias config No need to declare methods
axios.get(url,{
    
	headers:{
    token:'xxxx'} // Request header 
	params: {
     //get Request to pass parameters 
    	ID: 12345
  	},
})
// After using the alias post The parameter is passed to the second parameter of the method 
axios.post(url, data ,{
    
	headers:{
    token:'xxxx'} // Request header 
})

(3) establish axios example

import axios from "axios"

// establish axios example , You can merge the specified configuration with the configuration of the instance 
let instance = axios.create({
    
	headers:{
    token:'xxxx'}, // Request header 
	timeout: 1000 * 30,
	baseURL: 'https://some-domain.com/api/', // Automatically add to request url front 
})

instance.get(url,{
    
	params: {
     //get Request to pass parameters 
    	ID: 12345
  	},
})
instance.post(url,data,{
    })

3、 ... and , Process response results

1.axios Is based on promise Of http library , We can use .then Get the returned information

axios.get(url,{
    
	headers:{
    token:'xxxx'} // Request header 
	params: {
     //get Request to pass parameters 
    	ID: 12345
  	},
}).then(data=>{
    
	...
})

2. The returned information contains the following

{
    
  // `data`  Response provided by server 
  data: {
    },

  // `status`  From server response  HTTP  Status code 
  status: 200,

  // `statusText`  From server response  HTTP  State information 
  statusText: 'OK',

  // `headers`  Header of server response 
  headers: {
    },

   // `config`  Is the configuration information provided for the request 
  config: {
    },
 // 'request'
  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {
    }
}

3. Error information acquisition

// stay then Second parameter of 
axios.get(url,{
    
	headers:{
    token:'xxxx'} // Request header 
	params: {
     //get Request to pass parameters 
    	ID: 12345
  	},
}).then(data=>{
    
	...
},error=>{
    ....})

// Or use catch
axios.get(url,{
    
	headers:{
    token:'xxxx'} // Request header 
	params: {
     //get Request to pass parameters 
    	ID: 12345
  	},
}).catch(error=>{
    
	 if (error.response) {
    
      // Request succeeded , The returned status code is not 2xx,  for example 500,404 etc. 
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
    
      // The request was sent but no response was received , For example, request timeout 
      console.log(error.request);
    } else {
    
     // The request has not yet been sent , There was a mistake 
      console.log('Error', error.message);
    }
})

Four , Interceptor

1. stay axios in , We can use interceptors , stay Request issued or Response is then or catch Before processing Intercept them .

2. Request interceptor

//  Add a request interceptor 
axios.interceptors.request.use(
// Request sent successfully 
function (config) {
    
    //  What to do before sending the request 
    config.headers['x-token'] = 'xxxx'
    return config;
  },
// Request send failed 
function (error) {
    
    //  What do you do about the request error 
    return Promise.reject(error);
  });

3. Response interceptors

//  Add response interceptors 
axios.interceptors.response.use(
// The request is successful 
function (response) {
    
	const {
    status , data } = response //response Is the information returned 
    //  What to do with response data 
    return response.data ; //return The data of .then Acquired data 
  }, 
// request was aborted 
function (error) {
    
    //  What to do about response errors 
    return Promise.reject(error);
  });

5、 ... and , Use application/x-www-form-urlencoded

1. By default ,axios take JavaScript Object serialization to JSON. To use application / x-www-form-urlencoded Format send data , You can use the following methods .

import qs from "qs"
axios.post('/foo', qs.stringify({
     'bar': 123 }));

6、 ... and , matters needing attention

1. Based on the commonly used post and get Summarize the differences ,

2.get The requested parameters are in config Of params in , Or directly at url On ?id=1111&name=xxxx

3.post Request to pass parameter in config Of data in , When using aliases, the second parameter of the instance method

4.post When an object is requested to pass parameters , The default is application request , If you want to use application / x-www-form-urlencoded, To convert an object to id=1111&name=xxxx This form

copyright notice
author[Bean paste,],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/175/202206240445296990.html

Random recommended