问题描述
我设置了 axios.defaults.timeout = 1000;
我停止了为我提供服务的服务器API。
I stopped the server that provides me with the APIs.
但发送请求后超时需要超过1秒。
But it takes more than 1s to timeout after sending a request.
这就是我的请求看起来:
This is how my request looks:
import axios from 'axios';
axios.defaults.timeout = 1000;
return axios.post(`${ROOT_URL}/login/${role}`, creds).then((response) => {
console.log(response);
if(response.status === 200) {
// If login was successful, set the token in local storage
localStorage.setItem(`${role}_log_toks`, JSON.stringify(response.data));
// Dispatch the success action
dispatch(receiveLogin(response.data));
return response;
}
}).catch(err => {
console.log(err);
// If there was a problem, we want to
// dispatch the error condition
if(err.data && err.status === 404) {
dispatch(loginError(err.data));
} else {
dispatch(loginError('Please check your network connection and try again.'));
}
return err;
});
我也试过:
return axios.post(`${ROOT_URL}/login/${role}`, creds, {timeout: 1000}).then...
Axios不会停止提取,并在5-10分钟后最终显示网络错误。我知道还有其他技术可以处理超时,但为什么axios中的超时功能不起作用? axios不会停止提取的原因是什么?
Axios doesn't stop fetching and after 5 - 10 minutes it finally shows network error. I understand that there are other techniques to handle timeout but why doesn't the timeout feature in axios work? What could be the reason that axios doesn't stop fetching?
编辑:
如评论中所述,我也尝试过:
As mentioned in the comments, I have also tried:
import axios from 'axios';
const httpClient = axios.create();
httpClient.defaults.timeout = 500;
return httpClient.post(`${ROOT_URL}/login/${role}`, creds)
.then(handleResponse)
推荐答案
您需要创建axios http客户端的实例:
You need to create an instance of the axios http client:
const httpClient = axios.create();
httpClient.defaults.timeout = 500;
然后您可以按如下方式使用httpClient:
You can then use the httpClient as follows:
return httpClient.post(`${ROOT_URL}/login/${role}`, creds)
.then(handleResponse)
另外,您还可以在同一个配置中设置基本网址,而不是使用 $ {ROOT_URL}
:
On a side note you can also set the base url in the same config instead of using ${ROOT_URL}
:
httpClient.defaults.baseURL = ROOT_URL
这篇关于axios库中的超时功能无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!