Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Timeout doesn't work #647

Closed
rafalschmidt97 opened this issue Jan 10, 2017 · 23 comments
Closed

Timeout doesn't work #647

rafalschmidt97 opened this issue Jan 10, 2017 · 23 comments

Comments

@rafalschmidt97
Copy link

rafalschmidt97 commented Jan 10, 2017

Hi,
I cant implement timeout request.

What i did:

axios.defaults.timeout = 100000;

My action:

export function login(data) {
  return dispatch => {
    return axios.post('auth/login', null,{
      headers: {
        username: data.email,
        password: data.password,
      },
     timeout: 5000
    })
    .then(res => {
      const token = res.data.token;
      localStorage.setItem('Token', token);
      setAuthToken(token);
      dispatch(setAccount(jwtDecode(token)));

      return res;
    });
  };
}

And react side:

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!

@hoangtubatu
Copy link

hoangtubatu commented Jan 23, 2017

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
});

@Lxxyx
Copy link

Lxxyx commented Feb 7, 2017

Same problem.

@robcaldecott
Copy link

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
})

@camflan
Copy link

camflan commented Apr 27, 2017

Same, timeout doesn't work - I've implemented my own timeout functionality using CancelToken. I'd love to remove this cancelling boilerplate

@peng-hf
Copy link

peng-hf commented Jun 21, 2017

Still doesn't work on me either using React Native 0.42.3 ..
@camflan Would you show how you implemented your own timeout functionality with CancelToken ? Thanks :)

@camflan
Copy link

camflan commented Jun 21, 2017

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

@zhuyifan2013
Copy link

same issue!!

@zhuyifan2013
Copy link

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
    })
};

@frevib
Copy link

frevib commented Aug 24, 2017

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());
        }
    };
}

@montogeek
Copy link

@rshmiraf Is the issue fixed for you?

@rob-mcgrail
Copy link

Is there a reason to think this is fixed? There's no code change referenced in this or the linked Axios ticket.

@baijunjie
Copy link

same issue!

Sometimes timeout doesn't work, I have to use CancelToken.

@joelnet
Copy link

joelnet commented Jan 31, 2019

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`)

@nelsonomuto
Copy link

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'});
}

@rafalschmidt97
Copy link
Author

rafalschmidt97 commented Dec 11, 2019

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!

@benb1983
Copy link

This still isn't fixed in 0.19.2 btw...

abuiles pushed a commit to stellar/js-stellar-sdk that referenced this issue Jan 30, 2020
* 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
@epatrasc
Copy link

epatrasc commented Feb 21, 2020

This still isn't fixed in 0.19.2 btw...

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

@blombard
Copy link

blombard commented Mar 9, 2020

@epatrasc You can reproduce it like that :

const axios = require('axios');

axios({
    method: 'POST',
    url: 'http://example.com:81',
    data: {
      foo: 'bar'
    },
    timeout: 100
  })
  .then(data => console.log(data))
  .catch(error => console.log(error))

@arfa123
Copy link

arfa123 commented Apr 3, 2020

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");
});

@epatrasc
Copy link

epatrasc commented Apr 3, 2020

@epatrasc You can reproduce it like that :

const axios = require('axios');

axios({
    method: 'POST',
    url: 'http://example.com:81',
    data: {
      foo: 'bar'
    },
    timeout: 100
  })
  .then(data => console.log(data))
  .catch(error => console.log(error))

Hey thanks for the reply and the example.
So the problem is related to the POST request and is independent from the platform. both GET and POST but to reproduce the problem you need a valid server:port that never or is very very slow to respond.

@epatrasc
Copy link

epatrasc commented Apr 3, 2020

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

@jlgouwyapizr
Copy link

It seems the problem is not fixed yet.
I just encountered on my AWS lambda.

I will try with CancelToken soluce ! Thx

yodhcn added a commit to yodhcn/kikoeru-express that referenced this issue Apr 29, 2020
BUG 原因:连接 HVDB 服务器超时
axios/axios#647
@crizzs
Copy link

crizzs commented May 14, 2020

I am still facing this issue in our node app.
Upping this!!!

@axios axios locked and limited conversation to collaborators May 22, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests