Some knowledge about Axios

Posted by mhoard8110 on Wed, 22 Dec 2021 17:04:50 +0100

What is Axios?

Axios is a promise based HTTP library. In short, it can send get and post requests. When it comes to get and post, you should think of Jquery for the first time. After all, when Jquery was popular a few years ago, everyone used it. However, due to the emergence of Vue, React and other frameworks, Jquery is not so popular. It is also the emergence of Vue, React and other frameworks that prompted the emergence of 'Axios lightweight Library'. Because Vue and other frameworks do not need to operate Dom, Jquery does not need to be introduced JS.

Axios features

1. You can send XMLHttpRequests in the browser

2. It can be on node JS send http request

3. Support Promise API

4. Intercept requests and responses

5. Convert request data and response data

6. Be able to cancel the request

7. Automatically convert JSON data

8. The client supports security protection against XSRF attacks

What scenario is Axios used in?


It has been mentioned in the feature that the browser sends a request or Node Axios can be used to send requests from JS. Axios can be used for projects such as Vue, React and Node. If jQuery is used in your project, you don't need to kill one stone at this time. JQuery itself can send requests.

How does Axios work?


Installation module

npm install axios


Example (I)

// GET
axios.get('/user', {
  params: {
    ID: 12345
  }
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

// POST
axios.post('/user', {
  name: 'Javan',
  website: 'www.javanx.cn'
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});


The above parameters are optional
If you want to concurrent multiple requests, you can see the code below


Example (II)


In addition to the above methods, you can create requests by passing related configurations to axios, such as:

// POST
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});


grammar

axios(url[, config])


config

{
  // `URL ` is the server URL for the request
  url: '/user',

  // `Method ` is the method used when creating the request
  method: 'get', // The default is get

  // `baseURL 'will be automatically added before' URL ', unless' URL' is an absolute URL.
  // It can set a 'baseURL' to facilitate the delivery of relative URL s for axios instance methods
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest ` allows you to modify the request data before sending it to the server
  // It can only be used in the request methods of 'PUT', 'POST' and 'PATCH'
  // The function in the following array must return a string, or ArrayBuffer, or Stream
  transformRequest: [function (data) {
    // Arbitrary conversion of data

    return data;
  }],

  // `transformResponse ` it is allowed to modify the response data before passing it to then/catch
  transformResponse: [function (data) {
    // Arbitrary conversion of data

    return data;
  }],

  // `headers ` is the custom request header to be sent
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params ` is the URL parameter to be sent with the request
  // Must be a plain object or URLSearchParams object
  params: {
    ID: 12345
  },

  // `paramsSerializer ` is a function responsible for 'params' serialization
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `Data ` is the data sent as the request body
  // Only applicable to these request methods' put ',' post ', and' PATCH '
  // When 'transformRequest' is not set, it must be one of the following types:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // -Browser specific: FormData, File, Blob
  // -Node exclusive: Stream
  data: {
    firstName: 'Fred'
  },

  // `Timeout ` specifies the number of milliseconds that the request times out (0 means no timeout)
  // If the request takes longer than 'timeout', the request will be interrupted
  timeout: 1000,

  // `withCredentials ` indicates whether credentials are required for cross domain requests
  withCredentials: false, // default

  // `adapter ` allows custom processing of requests to make testing easier
  // Return a promise and apply a valid response (see [response docs] (#response API))
  adapter: function (config) {
    /* ... */
  },

  // `auth ` indicates that HTTP basic authentication should be used and credentials should be provided
  // This will set an 'Authorization' header, overwriting any existing custom 'Authorization' header set with 'headers'
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType ` indicates the data type of the server response. It can be 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // default

  // `Xsrfcookie name ` is the name of the cookie used as the value of xsrf token
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName ` is the name of the HTTP header that carries the value of xsrf token
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

  // `onUploadProgress ` allows processing progress events for uploads
  onUploadProgress: function (progressEvent) {
    // Handling of native progress events
  },

  // `onDownloadProgress ` allows processing progress events for downloads
  onDownloadProgress: function (progressEvent) {
    // Handling of native progress events
  },

  // `maxContentLength ` defines the maximum size of the allowed response content
  maxContentLength: 2000,

  // `validateStatus ` defines whether the status code for a given HTTP response is resolve or reject promise. If 'validateStatus' returns' true' (or set to 'null' or 'undefined'), promise will be resolved; Otherwise, promise will be rejecte d
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects ` is defined in node Maximum number of redirects for follow in JS
  // If set to 0, no redirection will follow
  maxRedirects: 5, // default

  // `httpAgent 'and' httpsAgent 'are on node JS is used to define the custom proxy used when executing http and https. Allow options to be configured like this:
  // `keepAlive ` is not enabled by default
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // 'proxy' defines the host name and port of the proxy server
  // `auth ` indicates that HTTP basic authentication should be used for connection proxy and provide credentials
  // This will set a 'proxy authorization' header, overwriting the existing custom 'proxy authorization' header set by using the 'header'.
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: : {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },
  // `cancelToken ` specifies the cancel token used to cancel the request
  // (see the Cancellation section later for more information)
  cancelToken: new CancelToken(function (cancel) {
  })
}


Example (III)


We can also create a new axios instance using custom configuration and intercept requests or responses before they are processed by then or catch.
 

// If the file name is http js
import axios from 'axios'

// Set the default value of the configuration when creating an instance
var instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

// Add request interceptor
instance.interceptors.request.use(function (config) {
  // What to do before sending the request
  /**
    1,For example, add request header information such as token
    2,Add loading per request, etc
  */
  return config;
}, function (error) {
  // What to do about request errors
  return Promise.reject(error);
});

// Add response interceptor
instance.interceptors.response.use(function (response) {
  // Do something about the response data
  /**
    1,Centralized processing of response data (such as error code processing)
  */
  return response;
}, function (error) {
  // Do something about response errors
  return Promise.reject(error);
});

export default instance

How to use HTTP js???

import http from 'xxx/http'

http({
  method: 'POST',
  url: '/user',
  data: {
    name: 'Javan',
    website: 'www.javanx.cn'
  }
}).then((response) => {
  // 200 response
}, (err) => {
  // 500 response
})


Example (IV)


How to cancel the interface???
Scenario: a search box will call the interface every time a character is entered. At this time, there is no way to know that the data of that interface is put back for the last time. You can only cancel the same interface initiated before, so there is a cancel interface.

 

var CancelToken = axios.CancelToken;
var source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // Processing error
  }
});

// Cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');


Example (V)


Encapsulate Axios related requests

axios.defaults.baseURL = "http://127.0.0.1:8888/api/front / "; / / request address
axios.defaults.timeout = 5000; //Timeout
axios.defaults.withCredentials = false; //Indicates whether credentials are required for cross domain requests

// axios.defaults.headers['Content-Type']='application/json;charset=UTF-8';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.interceptors.request.use((config) => {
    //Here you can write the interception operation you want
    return config;
}, (error) => {
    return Promise.reject(error);
});

Sub packed according to the above axios Objects, encapsulating get,post,put,delete request 
/**
 * post Method, corresponding to the post request
 * * @param {String} url [Requested url address]
 * * @param {Object} params [Parameters carried during request]
 * *@param {headers}headers[[request header parameters]
 **/

function get(url, params, headers) {
    return new Promise((resolve, reject) => {
        console.log(resolve);
        axios.get(url, {
            params,
            headers
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}
function post(url, params, headers) {
    return new Promise((resolve, reject) => {
        axios.post(url, params, headers).then((res) => {
            resolve(res)
        }).catch((err) => {
            // debugger
            reject(err)
        })
    })
}

function put(url, params, headers) {
    return new Promise((resolve, reject) => {
        axios.put(url, params, headers).then((res) => {
            resolve(res)
        }).catch((err) => {
            // debugger 
            reject(err)
        })
    })
}

function del(url, params, headers) {
    return new Promise((resolve, reject) => {
        axios.delete(url, {
            data: params,
            headers
        }).then((res) => {
            resolve(res)
        }).catch((err) => {
            // debugger
            reject(err)
        })
    })
}


summary


axios is a very lightweight HTTP library, which is well packaged and easy to use. Most browsers support it. After all, it is used with vue, React and other front-end technologies at this stage, so the adaptation of low-level IE is no longer considered. Overall, it's great.

Some information reference sources: https://www.imooc.com/article/287900

Topics: Java Javascript