Front end training - intermediate stage (42) - use of axios and how to combine it with vue

The most basic front-end is HTML+CSS+Javascript. Mastering these three technologies is just an introduction, but it is only an introduction. Now the definition of front-end development is far more than that. Front end small class (HTML/CSS/JS), in line with the central idea of improving the technical level and laying a solid foundation for basic knowledge, we have a class (every Thursday).

Today, let's take a look at the library of axios. Basically, most vue applications have used axios.
Vue resource is generally used in early Vue. When there is no Vue, it is the $. Of the invincible jQuery ajax.

axios features

  • Support browser environment and Node environment
  • support Promise , chain call.
  • It has interceptor function, which can intercept requests and responses
  • There is a converter function, which can convert request data and response data
  • Cancel request (fetch does not support cancellation), the logic implemented by CancelToken
    Axios' cancel token API is based on cancelable promises proposal

API

Request method

  • axios(config) is my favorite method, which is convenient for modification and batch modification of other methods (for example, I encapsulated an axios automatic retry library, which is fast to change).
  • axios(url[, config])
  • axios.request(config)
  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])

Request configuration 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'})
  },

  // `The data requested is sent as the data subject
  // 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 the request times out (0 means no timeout)
  // If the call cost exceeds the '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 The maximum number of redirects of 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 '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) {
  })
}

response

{
  // `data ` response provided by the server
  data: {},

  // `Status ` HTTP status code from the server response
  status: 200,

  // `statusText ` HTTP status information from the server response
  statusText: 'OK',

  // `headers ` the header of the server response
  headers: {},

  // `config ` is the configuration information provided for the request
  config: {}
}

Other methods

Helper function for handling concurrent requests

  1. axios.all(iterable) can be understood as promise all
  2. axios.spread(callback) breaks down the response into input parameters one by one
  3. axios.create([config]) create a new Axios instance with custom configuration. For example, for different businesses, package it for targeted configuration. It can also be configured by default, such as Axios defaults. headers. post['Content-Type'] = 'application/x-www-form-urlencoded';

    Because multiple configurations are involved, there will be one priority. The order is: in lib / defaults JS, then the defaults attribute of the instance, and finally the config parameter of the request. The latter will take precedence over the former. Here is an example:

    // Create an instance using the default values of the configuration provided by the library
    // At this time, the default value of timeout configuration is ` 0`
    var instance = axios.create();
    
    // Override library timeout defaults
    // Now, all requests will wait 2.5 seconds before timeout
    instance.defaults.timeout = 2500;
    
    // Override timeout settings for requests that are known to take a long time
    instance.get('/longRequest', {
      timeout: 5000
    });

Serialize paramsSerializer

Requirements are quite common. For example, how to display arrays?

paramsSerializer is a function (e.g https://www.npmjs.com/package... http://api.jquery.com/jquery.param/)

paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
},

Interceptor

// Add request interceptor
axios.interceptors.request.use(function (config) {
    // What to do before sending the request
    return config;
  }, function (error) {
    // What to do about request errors
    return Promise.reject(error);
  });

// Add response interceptor
axios.interceptors.response.use(function (response) {
    // Do something about the response data
    return response;
  }, function (error) {
    // Do something about response errors
    return Promise.reject(error);
  });
  
// Remove interceptor  
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

Cease Request

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.');

matters needing attention

  1. axios relies on native ES6 Promise Implementation support . If your environment does not support ES6 Promise, you can use polyfill . Android 4 x. Don't ask me why I'm compatible with such a low version. Asking is crying
  2. responseType indicates the data type of the server response, which can be 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'.
    stream can only be used in Node.
    Arraybuffer, blob and document can only be used in the browser.
  3. Some services using proxy in node will be inaccessible. Consider using Axios HTTPS proxy fix

Wechat official account: front-end linong

reference

  1. Front end training directory, front end training plan and front end training plan

Tags: Javascript Front-end html5 Vue.js html

Posted by jonstu on Fri, 13 May 2022 20:54:19 +0300