Timeout feature in the axios library is not working

I have set axios.defaults.timeout = 1000;

I stopped the server that provides me with the APIs.

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

I have also tried:

return axios.post(`${ROOT_URL}/login/${role}`, creds, {timeout: 1000}).then...

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?

Axios version 0.9.1

EDIT: 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)

You need to create an instance of the axios http client:

const httpClient = axios.create();
httpClient.defaults.timeout = 500;

You can then use the httpClient as follows:

return axios.post(`${ROOT_URL}/login/${role}`, creds)
  .then(handleResponse)

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
链接地址: http://www.djcxy.com/p/33520.html

上一篇: NullReferenceException与MSIL

下一篇: axios库中的超时功能不起作用