axios: Timeout doesn't work

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!

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 15
  • Comments: 23

Commits related to this issue

Most upvoted comments

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

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

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!

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

I will try with CancelToken soluce ! Thx

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

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

This still isn’t fixed in 0.19.2 btw…

@rshmiraf Is the issue fixed for you?

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