编程知识 cdmana.com

Vue combined with Axios interface timeout unified processing

Official account : WeChat search web Full stack upgrade ; Receive more dry goods

The opening

When the Internet is slow ; When the server is not in the Mainland , If the interface data request does not come back, it will be reported as an error , Here I would like to share the processing method of project request timeout in our company , I hope it will help after watching .

axios I won't say much about the basic usage , Details direct stamp : https://www.kancloud.cn/yunye/axios/234845

Mainly thinking : Yes axios Ask the interceptor to work

step

Solution 1 :

shortcoming :

  1. Just re request 1 Time , If it's over time , It stops , No more requests ;
  2. The background allows you to re initiate a request only once ( Can't supercharge the server 、 Waste bandwidth, unlimited requests )

Have a look axios Source code , After a timeout , It's going to be at the interceptor axios.interceptors.response Catch the error message , And error.code = "ECONNABORTED",


//  request timeout
request.ontimeout = function handleTimeout() {
  reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', request));
  //  Cancel the request
  request = null;
};
Copy code

Global timeout processing scheme :

//  Request interceptor 
axios.interceptors.response.use(function(response){
    //  Request successfully processed callback
}, function(error){
    //  request was aborted 、 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 code

Solution 2 : recommend

// stay main.js Set the number of global requests , Requested clearance 
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 , Please refuse
 if(!config || !config.retry) return Promise.reject(err);
 //  Set the number of variable tracking retries
 config.__retryCount = config.__retryCount || 0;
 //  Check if the maximum total number of retries has been reached
 if(config.__retryCount >= config.retry) {
  //  Throw error messages
  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 , Re request
 return backoff.then(function() {
  return axios(config);
 });
});
Copy 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 code

Configuration parameters :

  • retry : The number of requests retried after the first failed request .
  • retryDelay: The number of milliseconds to wait between failed requests ( The default is 1). The above is the scheme of request timeout processing .

Expand axios Custom configuration create a new axios example Request configuration information Requst Config Here are some common configuration options for development

axios.create([config])
var instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header''foobar'}
});
Copy code

config To configure :

// newly build  config.js
import Qs from 'qs'
{
 // Requested interface , At the time of request , Such as axios.get(url,config); there url Will overwrite config Medium url
 url: '/user',
 //  The request method is the same as above
 method: 'get', // default
 //  Basics url Prefix
 baseURL: 'https://some-domain.com/api/',   
 transformRequest: [function (data) {
   //  Here you can process the request data before sending the request , such as form-data Format, etc , Here you can use the... Introduced at the beginning Qs( This module is being installed axios It's already installed , No additional installation is required )
  data = Qs.stringify({});
  return data;
 }],
 transformResponse: [function (data) {
  //  The returned data is processed ahead of time here
  return data;
 }],
 //  Request header information
 headers: {'X-Requested-With''XMLHttpRequest'},
 //parameter Parameters
 params: {
  ID: 12345
 },
 //post Parameters , Use axios.post(url,{},config); If there is no extra, you have to use an empty object , Otherwise, an error will be reported
 data: {
  firstName: 'Fred'
 },
 // Set timeout
 timeout: 1000,
 // Return data type
 responseType: 'json', // default
}
Copy code

ending

Source of the article : My own blog post https://www.cnblogs.com/ljx20180807/p/9921347.html

版权声明
本文为[Mr Lai]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224152607759c.html

Scroll to Top