基于Vue2的项目构建记录之二:Axios的使用细节
[ 2018/05/07, Vue , 3489阅, 1评 ]
之前是写angularJS的,现在转到Vue,一开始傻傻滴以为它也自带了http服务,然而并非如此。
在Vue1.0的时候有一个官方推荐的 ajax 插件 vue-resource,但是自从 Vue 更新到 2.0 之后,官方就不再更新 vue-resource。
权衡利弊之后最终选择了axios,毕竟辣么哆人在用它,也能满足项目需求。下面记录一些使用过程中遇到的问题。

官方源码及文档:https://github.com/axios/axios

这里还有个不错的中文“说明书”:vue2.0项目实战(3)使用axios发送请求

具体使用方法以及拦截器什么的本文不必记录,官方文档已经写得很详细了,本文仅记录“官方没有的东西”吧,O(∩_∩)O哈哈~

axios发起post请求时同一接口请求两次的问题(第一次OPTIONS第二次才POST)

Axios执行post发送两次请求1.jpg

console一下,发现:

Axios执行post发送两次请求2.jpg

于是改成:

Axios执行post发送两次请求3.jpg

再试一下就行了:

Axios执行post发送两次请求4.jpg

当然,造成这种情况也可能还有其他原因,可参考:

Axios 执行post发送两次请求的小坑

解决 axios 跨域时,发送 post 请求变 options 的问题

请求超时问题

比较完美的解决方案如下:

axios.defaults.retry = 4;
axios.defaults.retryDelay = 1000;

axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
    var config = err.config;
    // If config does not exist or the retry option is not set, reject
    if(!config || !config.retry) return Promise.reject(err);
    
    // Set the variable for keeping track of the retry count
    config.__retryCount = config.__retryCount || 0;
    
    // Check if we've maxed out the total number of retries
    if(config.__retryCount >= config.retry) {
        // Reject with the error
        return Promise.reject(err);
    }
    
    // Increase the retry count
    config.__retryCount += 1;
    
    // Create new promise to handle exponential backoff
    var backoff = new Promise(function(resolve) {
        setTimeout(function() {
            resolve();
        }, config.retryDelay || 1);
    });
    
    // Return the promise in which recalls axios to retry the request
    return backoff.then(function() {
        return axios(config);
    });
});

也可以单独定义请求次数和间隙:

axios.get('/some/endpoint', { retry: 5, retryDelay: 1000 })
    .then(function(res) {
        console.log('success', res.data);
    })
    .catch(function(err) {
        console.log('failed', err);
    });

该方案来自:https://github.com/axios/axios/issues/164#issuecomment-327837467

相关细节可参考:解决在vue中axios请求超时的问题

有朋自远方来...评论一下呗O(∩_∩)O

  • 评论(1)

    天津网站建设 [ 回复 ]
    2018-10-09 17:25

    感谢您分享