Public account: wechat search front end tool person; Take more dry goods

The opening

When the Internet is slow; Or when the server of the company is not in mainland China, I believe you must have encountered the situation that the interface data request does not return and the error is reported over time. Here I share the processing method of the project request over time of my company, hoping to get help after reading it.

Axios basic usage is not much said, details directly: https://www.kancloud.cn/yunye/axios/234845

The main idea: work on the AXIos request blocker

steps

Solution 1:

Disadvantages:

  1. It only rerequests once, and if it times out again, it stops, it doesn’t ask again;
  2. The background only allows you to re-initiate a request once (no supercharging the server, wasting unlimited bandwidth)

Looked axios source code, after a timeout, the interceptor axios. There interceptors. Response captured error message, and the error. Code = “ECONNABORTED”,



// The request timed out

request.ontimeout = function handleTimeout() {

  reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', request));

// Cancel the request

  request = null;

};

Copy the code

Global timeout handling scheme:

// Request interceptor

axios.interceptors.response.use(function(response){

// The request successfully processed the callback

}, function(error){

// Request failed, error handling callback

    var originalRequest = error.config; 

    if(error.code == 'ECONNABORTED' && error.message.indexOf('timeout')! = 1 &&! originalRequest._retry){

       originalRequest._retry = true

       return axios.request(originalRequest);

    }

});

Copy the code

Solution 2: Recommendation

// Set the global number of requests in main.js, and the interval between requests

axios.defaults.retry = 4;

axios.defaults.retryDelay = 1000;

axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {

 var config = err.config;

// If config does not exist or the retry option is not set, reject it

 if(! config || ! config.retry)return Promise.reject(err);

// Set the number of variable trace retries

 config.__retryCount = config.__retryCount || 0;

// Check whether the maximum number of retries has been reached

 if(config.__retryCount >= config.retry) {

// Throw an error message

  return Promise.reject(err);

 }

// Increase the number of request retries

 config.__retryCount += 1;

// Create a new asynchronous request

 var backoff = new Promise(function(resolve) {

  setTimeout(function() {

   resolve();

  }, config.retryDelay || 1);

 });

// Return axios information to request again

 return backoff.then(function() {

  return axios(config);

 });

});

Copy the code

Use:

axios.get('/some/endpoint', { retry: 5, retryDelay: 1000 })

    .then(function(res) {

        console.log('success', res.data);

    })

    .catch(function(err) {

        console.log('failed', err);

    });

Copy the code

Configuration parameters:

  • retry: Indicates the number of retries after the first failed request.
  • retryDelay: Number of milliseconds to wait between failed requests (default: 1). This is the scenario for handling timeout requests.

Extending axiOS custom configuration Creating a new AXIOS instance requesting configuration information Requst Config The following are some configuration options commonly used for development

axios.create([config])

var instance = axios.create({

  baseURL: 'https://some-domain.com/api/'.

  timeout: 1000,

  headers: {'X-Custom-Header''foobar'}

});

Copy the code

The config configuration:

/ / the new config. Js

import Qs from 'qs'

{

// The requested interface at the time of the request, such as axios.get(url,config); The url here overrides the url in config

 url: '/user'.

// Do the same as above

 method: 'get', // default

// Base URL prefix

 baseURL: 'https://some-domain.com/api/'.

 transformRequest: [function (data) {

// We can use the Qs module introduced at the beginning of the request (this module was installed when axios was installed, so we don't need to install it).

  data = Qs.stringify({});

  return data;

}].

 transformResponse: [function (data) {

// The returned data is processed ahead of time

  return data;

}].

// Request header information

 headers: {'X-Requested-With''XMLHttpRequest'},

/ / parameter parameters

 params: {

  ID: 12345

 },

// The post argument, using axios.post(url,{},config); An empty object must be used if there is no extra, otherwise an error will be reported

 data: {

  firstName: 'Fred'

 },

// Set the timeout period

 timeout: 1000,

// Return the data type

 responseType: 'json', // default

}

Copy the code

At the end

Article source: your blog at https://www.cnblogs.com/ljx20180807/p/9921347.html