Operation of setting timeout timeout by axios in vue
- 2021-08-10 06:50:38
- OfStack
When doing vue project, due to the large amount of data query, the foreground often has to wait for a long time when calling interface data, so it is necessary to set a timeout. When it exceeds the setting time, it will return a state to the page, so that users do not need to wait straight.
Through the official website api query, there are not many explanations on its timeout, but it is very similar to the request in Jquery
Jquery Request Mode
$.ajax({
url: ' Interface address ',
type:'get', // Request mode get Or post
data:{}, // Parameters passed by the request
dataType: 'json', // Data format returned
timeout: 4000, // Set time-out in milliseconds
success: function(result) {
console.log('OK')
},
error: console.log('error')
})
Request mode in vue:
axios.post( // Request mode
url, // Interface address
params, // Transfer parameter
{timeout: 1000 * 60 * 2}) // Set timeout in milliseconds
.then(function(res){
console.log(res);
}).catch((error) => {
console.log('error')
})
So you can set the request timeout through timeout in the request again
Additional knowledge: In vue, axios request interface is used to deal with network failure and network timeout problems, and axios interceptor
The front end often has to deal with the error information of the server. This site is the first time to do it, and it has encountered many problems
First, it is the method of encapsulating the request data
import Vue from 'vue';
import axios from 'axios';
import qs from 'qs';
import wx from 'weixin-js-sdk';
import {
Toast
} from 'mint-ui';
axios.defaults.timeout = 10000;
// Intercept
axios.interceptors.request.use(function (config) {
return config
}, function (error) {
return Promise.reject(error);
})
axios.interceptors.response.use(
response => {
if (typeof(response) != 'String'&&response.data.errno !== 0 && response.config.url.indexOf('searchorderoyidornumber') < 0 && response.config.url.indexOf('upload') < 0) {
response.data['data'] = response.data['data'] || {};
Toast(response.data.errmsg)
}
if (typeof(response) != 'String'&&response.data.errno == 3521) {
localStorage.clear();
location.href = '#/login'
}
return response.status == 200 ? response.data : response;
// return response
},
error => {
//String(error).toLowerCase().indexOf('timeout')
if (error && error.stack.indexOf('timeout') > -1) {
Toast(' Request timeout ')
}
// let config = error.config;
// if (!config || !config.retry) return Promise.reject(err);
// config.__retryCount = config.__retryCount || 0;
// // Check if we've maxed out the total number of retries
// if (config.__retryCount >= config.retry) {
// // Reject with the error
// return Promise.reject(err);
// }
// // Increase the retry count
// config.__retryCount += 1;
// // Create new promise to handle exponential backoff
// var backoff = new Promise(function (resolve) {
// setTimeout(function () {
// resolve();
// }, config.retryDelay || 1);
// });
// // Return the promise in which recalls axios to retry the request
// return backoff.then(function () {
// return axios(config);
// });
}
);
let axios_post = function (url, params) {
return new Promise((resolve, reject) => {
if (!localStorage.getItem('token') || localStorage.getItem('token') == '') {
axios.get('/gettoken').then((res) => {
localStorage.setItem('token', res.data.token)
axios.post(url, qs.stringify(params),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(res => {
resolve(res)
}).catch(err => {
reject(err)
})
}).catch(err => {
reject(err)
})
} else {
params = url.indexOf('login') > -1 ? {
...params,
_token: localStorage.getItem('token')
} : {
...params,
_token: localStorage.getItem('token'),
S: localStorage.getItem('S'),
U: localStorage.getItem('U')
}
let options = {};
options['maxContentLength'] = 1024000000;
if(url.indexOf('uplpoad') > -1){
options['timeout'] = 1000 * 30;
}
axios.post(url, params, options).then(res => {
resolve(res)
}).catch(err => {
reject(err)
})
}
})
}
let axios_get = function (url, params) {
let _params = typeof (params) == 'object' ? params : {}
_params = {
..._params,
S: localStorage.getItem('S'),
U: localStorage.getItem('U')
}
return new Promise((resolve, reject) => {
axios.get(url, {
'params': _params
}).then(res => {
if (res.errno !== 0) {
reject(res)
}
resolve(res)
}).catch(err => {
reject(err)
})
})
}
let getCookie = function(cookieName) {
var cookieValue = "";
if (document.cookie && document.cookie != '') {
var cookies = decodeURIComponent(document.cookie).split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// if (cookie.substring(0, cookieName.length + 1).trim() == cookieName.trim() + "=") {
// cookieValue = cookie.substring(cookieName.length + 1, cookie.length);
// break;
// }
var cookie = cookies[i].trim();
var cookieArr = cookie.split('=');
if(cookieArr[0] == cookieName.trim()){
cookieValue = cookieArr[1];
break;
}
}
}
return cookieValue;
}
let setCookie = function(name,value){
var Days = 30;
var exp = new Date();
exp.setTime(exp.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
Vue.prototype.$http = axios;
Vue.prototype.$get = axios_get;
Vue.prototype.$post = axios_post;
Vue.prototype.$getCookie = getCookie;
Vue.prototype.$setCookie = setCookie;
this. $post () can be used directly in the component.