【问题标题】:How to set timeout for get request using Axios in Vue.js如何在 Vue.js 中使用 Axios 设置获取请求的超时时间
【发布时间】:2018-08-20 12:09:00
【问题描述】:

如何在 Vue.js 和 Webpack 中使用 axios 为 GET 请求设置超时? 例如我有这个代码

axios.get("myURL").then(function(response) {
        // code 
    } 

我尝试将 {timeout:3000} 作为参数包含在内,但它不起作用

【问题讨论】:

  • axios.get("myURL", { timeout: 3000 }) 应该可以工作,控制台中是否显示任何错误?
  • 不,我没有错误。我试图创建一个 axios 实例 axios({ method: 'get', url: 'myURL', timeout: 5000, }) 但我仍然没有超时.. 我只得到一次响应
  • 但是为什么你会得到它不止一次呢?
  • 我想每 5 秒发送一个新的 GET 请求来测试数据。我得到的 JSON 有随机数据,每次我发送请求时都会改变..
  • 那你在找setInterval: developer.mozilla.org/en-US/docs/Web/API/… axios' timeout 用于“取消”请求,如果响应没有在 X 毫秒内到达

标签: vue.js axios


【解决方案1】:

据我了解,Axios 中的timeoutresponse timeout,而不是connect timeout。您可以尝试使用cancelToken 功能

const connectToServer = ip => {
    let source = CancelToken.source();
    setTimeout(() => {
        source.cancel();
    }, 3000);
    return axios.get(ip + '/config', {cancelToken: source.token}).then((result) => {
        // My logic
    })
};

这将永远取消,或者如果您只想在没有响应的情况下取消:

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

【讨论】:

    猜你喜欢
    • 2019-02-21
    • 2018-08-28
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    • 2020-01-19
    • 2020-05-21
    • 1970-01-01
    相关资源
    最近更新 更多