to your account
localStorage.setItem('Token', token);
setAuthToken(token);
dispatch(setAccount(jwtDecode(token)));
return res;
this.props.login(this.state).then(
(res) => {
console.log('sign-in');
console.log(res);
browserHistory.push('/student/dashboard');
(err) => {
console.log('sign-in error');
console.log(err.response.data);
alert(err.response.data.message);
//isLoading: false
Where i made mistake?
Thanks for every answers!
Timeout doesn't work too on react native 0.39
This is my code:
axios.get('http://10.0.2.2:8080/api/login', {
params: {
name: 123,
pass: 456,
timeout: 1000,
.then((response) => {
// code here
.catch((error) => {
// code here
Same issue here with Chrome (Windows). Chrome seems to ignore any timeout setting. I'm setting it when making a request like this:
axios({
url: 'myurl',
method: 'post',
data: data,
timeout: 1000
Sure! My actual implementation is using redux-saga, which might be confusing if you're not used to using generators. If you are, I'm happy to show that too.
Here's a quickly written, slightly contrived, (and never executed 😄 ) example for you that should help.
import { axios, CancelToken } from "axios"
function updateUserInfo(data, cancel) {
return axios
.post(URL, data, {
// CancelToken takes a func that has the cancel function for it's param
// we'll set it to a prop on our cancel object that we passed in. Then we'll
// call this function where/when we need to cancel this request
cancelToken: new CancelToken(c => (cancel.exec = c)),
.then(r => r) // return the response
.catch(err => {
throw err // throw our error because the request failed
function submitForm(formData) {
// declare our cancel object to hold the cancel func.
// this has to be an object to exploit JS passing objects by reference and not value
let cancel = { exec: null }
const results = updateUserInfo(formData, cancel)
.then(resp => console.log(resp))
.catch(err => {
throw err
setTimeout(() => {
if (!results.ok) {
// if the timeout fires, and our results didn't come back
// then we'll call the cancel func set by CancelToken
cancel.exec()
}, 5000)
cc @MrLyfing
I found the timeout in axios is response timeout , not connection timeout , for example if you connect a local ip address 192.168.11.11 which dose not exist, it will take a long time , the timeout looks like invalid , but if you connect to a normal , well-connected server , the timeout take effects.
My platform is react-native.
So I solve this problem by the method provided by @camflan , thanks very much , my code :
const connectToServer = ip => {
let source = CancelToken.source();
setTimeout(() => {
source.cancel();
}, 300);
return axios.get(ip + '/config', {cancelToken: source.token}).then((result) => {
// My logic
raviqqe, frevib, mstrzele, amazecc, jonfreeland, nshoes, szymonjuskowiak, guimeira, treardon17, AndyChingAtBiB, and 34 more reacted with thumbs up emoji
eneserdogan, mikhailkopev, PARAGJYOTI, patrickrbc, and UseinAkbar reacted with hooray emoji
abey-alex, patrickrbc, and UseinAkbar reacted with heart emoji
All reactions
Solution of @camflan / @zhuyifan2013 works for me with React-Native 0.41.2 on Android. @zhuyifan2013's code calls always calls source.cancel(). Writing it like this would make it only cancel when there is no response:
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());
Still an issue in 2019. I have abandoned the timeout option since it is unreliable. Unreliable axios timeout is making my application unreliable. (a single unresolved promise prevents the entire app from continuing).
Now I must manually timeout axios using the CancellationToken method listed above.
I have created this helper function that works for my project:
const config = {
timeout: 1000
const axiosGet = (url, options = {}) => {
const abort = axios.CancelToken.source()
const id = setTimeout(
() => abort.cancel(`Timeout of ${config.timeout}ms.`),
config.timeout
return axios
.get(url, { cancelToken: abort.token, ...options })
.then(response => {
clearTimeout(id)
return response
// example usage
axiosGet(`${url}/status.json`)
vsimko, sadeghhosseini, kylemh, chrisrickard, JinWangQ, sumesh1993, imdaniele, khasky, mkkravchenkoo, bournean, and 4 more reacted with thumbs up emoji
arfa123 reacted with hooray emoji
arfa123 reacted with rocket emoji
All reactions
I created a wrapper for this to make is simply throw a timeout error you can catch
https://www.npmjs.com/package/@nelsonomuto/axios-request-timeout
import axiosRequest from '@nelsonomuto/axios-request-timeout';
try {
await axiosRequest({
url: 'https://www.cnn.com/',
method: 'GET',
timeout: 10
} catch(error) {
console.log({ error });
expect(error).toEqual({'message': 'timeout cancel'});
Wow. I've opened this issue almost three years ago and since then people still encounter problems when it comes to timeout. I think the axios team might forgot about this one so next time instead of adding another comment consider opening a new one issue (hopefully that will change anything). You can always attach this as a reference and for now, I'll close it. Good luck guys!
raviqqe, rob-mcgrail, karimkhamwani, xang555, and lpinto-axway reacted with laugh emoji
broom9 reacted with confused emoji
All reactions
Axios timeout doesn't catch missing urls, e.g. those with no response so we use the axios cancel token to ensure the timeout.
axios/axios#647
axios/axios#1503
* Revert PR https://github.com/stellar/js-stellar-sdk/pull/465/files
* Use axios CancelToken to ensure timeout
Axios timeout doesn't catch missing urls, e.g. those with no response so we use the axios cancel token to ensure the timeout.
axios/axios#647
axios/axios#1503
* adjustments to get tests to pass
Hi, is your problem on nodejs platform?
If so what version?
I'm trying to reproduce this issue on my local machine (nodejs 10 and 8) and timeout always works.
From the previous comments on this issue it looks like related to browser or mobile environments.
@benb1983
I solved the problem by adding timeout into the axios configuration before data parameter. For some reason, timeout parameter will not work if placed after the data parameter.
axios({
method: 'post',
timeout: 1000,
url: 'http://192.168.0.1:5000/download',
data: {
access: data.token
.then(function (response) {
alert(response.data);
.catch(function (error) {
alert("There was an error in communicating to server");
I solved the problem by adding timeout into the axios configuration before data parameter. For some reason, timeout parameter will not work if placed after the data parameter.
axios({
method: 'post',
timeout: 1000,
url: 'http://192.168.0.1:5000/download',
data: {
access: data.token
.then(function (response) {
alert(response.data);
.catch(function (error) {
alert("There was an error in communicating to server");
I have tried with both timeout before and after but same result, there's a timeout but after ~1min (timeout is set to 100ms).
--> node test.js 0.13s user 0.05s system 0% cpu 1:15.47 total
I used @arfa123's example code for testing.
this is the result:
time node test.js
running
end of the code not of the execution
{ Error: connect ETIMEDOUT 93.184.216.34:81
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1107:14)
errno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
address: '93.184.216.34',
port: 81,
config:
{ url: 'http://example.com:81',
method: 'post',
data: '{"foo":"bar"}',
headers:
{ Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json;charset=utf-8',
'User-Agent': 'axios/0.19.2',
'Content-Length': 13 },
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 100,
adapter: [Function: httpAdapter],
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus] },
request:
Writable {... },
writable: true,
_events:
[Object: null prototype] {
response: [Function: handleResponse],
error: [Function: handleRequestError] },
_eventsCount: 2,
_maxListeners: undefined,
_options:
{ protocol: 'http:',
maxRedirects: 21,
maxBodyLength: 10485760,
path: '/',
method: 'POST',
headers: [Object],
agent: undefined,
agents: [Object],
auth: undefined,
hostname: 'example.com',
port: '81',
nativeProtocols: [Object],
pathname: '/' },
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 13,
_requestBodyBuffers: [ [Object] ],
_onNativeResponse: [Function],
_currentRequest:
ClientRequest {
_events: [Object],
_eventsCount: 6,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: true,
socket: [Socket],
connection: [Socket],
_header:
'POST / HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nContent-Type: application/json;charset=utf-8\r\nUser-Agent: axios/0.19.2\r\nContent-Length: 13\r\nHost: example.com:81\r\nConnection: close\r\n\r\n',
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
timeout: undefined,
method: 'POST',
path: '/',
_ended: false,
res: null,
aborted: undefined,
timeoutCb: [Function: emitRequestTimeout],
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable: [Circular],
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]: [Object] },
_currentUrl: 'http://example.com:81/' },
response: undefined,
isAxiosError: true,
toJSON: [Function] }
node test.js 0.13s user 0.05s system 0% cpu 1:15.47 total