如何在Vue.js和Webpack中使用axios为GET请求设置超时? 例如,我有此代码
axios.get("myURL").then(function(response) {
// code
}
我尝试将{timeout:3000}用作参数,但不起作用
答案 0 :(得分:2)
据我了解,Axios中的timeout
是response timeout
,而不是connect timeout
。您可以尝试使用cancelToken
功能
const connectToServer = ip => {
let source = CancelToken.source();
setTimeout(() => {
source.cancel();
}, 3000);
return axios.get(ip + '/config', {cancelToken: source.token}).then((result) => {
// My logic
})
};
这将始终取消,或者如果您仅希望在没有响应的情况下取消:
function loginButtonPressed(username, password) {
return async (dispatch) => {
const source = CancelToken.source();
try {
let response = null;
setTimeout(() => {
if (response === null) {
source.cancel();
}
}, 4000);
dispatch(authenticationPending());
response = await axios.post('auth/login',
{username, password},
{cancelToken: source.token});
dispatch(authenticationSuccess());
} catch (error) {
dispatch(authenticationFailed());
}
};
}