zoukankan      html  css  js  c++  java
  • vue-resource请求超时timeout设置

    vue-resource请求超时timeout设置

    请求超时设置通过拦截器Vue.http.interceptors实现具体代码如下

    main.js里在全局拦截器中添加请求超时的方法

    方法1:超时之后会调用请求中的onTimeoutd方法,then方法不会执行

    Vue.http.interceptors.push((request, next) => {
        let timeout;
        // 如果某个请求设置了_timeout,那么超过该时间,会终端该(abort)请求,并执行请求设置的钩子函数onTimeout方法,不会执行then方法。
        if (request._timeout) {
            timeout = setTimeout(() => {
                if(request.onTimeout) {
                    request.onTimeout(request);
                    request.abort()
                }  
            }, request._timeout);
        }
        next((response) => {
           clearTimeout(timeout);
        return response;
        })
    })
    

    页面中用到vue-resource请求的地方如下设置即可。

    this.$http.get('url',{
                params:{.......},
           ......
               _timeout:3000,
               onTimeout: (request) => {
                   alert("请求超时");
               }
         }).then((response)=>{
                   
    });
    

     方法2:超时之后可以在then的第二个error方法中获取,私以为这个方法更好一些

    main.js中设置如下

    Vue.http.interceptors.push((request, next) => {
        let timeout;
        // 這裡改用 _timeout
        if (request._timeout) {
            timeout = setTimeout(() => {
            //自定义响应体 status:408,statustext:"请求超时",并返回给下下边的next
                next(request.respondWith(request.body, {
                     status: 408,
                     statusText: '请求超时'
                }));
                
            }, request._timeout);
        }
        next((response) => {
        console.log(response.status)//如果超时输出408
        return response;
        })
    })
    页面请求设置
    
    this.$http.get(`repairs/${this.repairs_id}`,{
                    params:{with:'room;user'},
                    _timeout:100,//设置超时时间
                }).then((response)=>{
                },(err)=>{
                    console.log(err.status);//如果超时,此处输出408
    });
    
    /** 
     *             ,%%%%%%%%, 
     *           ,%%/\%%%%/\%% 
     *          ,%%%c "" J/%%% 
     * %.       %%%%/ o  o \%%% 
     * `%%.     %%%%    _  |%%% 
     *  `%%     `%%%%(__Y__)%%' 
     *  //       ;%%%%`-/%%%'
     * ((       /  `%%%%%%%' 
     *  \    .'          | 
     *   \  /         | | 
     *    \/         ) | | 
     *              /_ | |__ 
     *     (___________))))))) 攻城湿 
     * 
     *        _       _ 
     * __   _(_)_   _(_) __ _ _ __ 
     *   / /   / / |/ _` |'_  
     *   V /| | V /| | (_| | | | | 
     *   \_/ |_| \_/ |_|\__,_|_| |_| 
     */ 

    参考文章  https://segmentfault.com/q/1010000005800495/a-1020000005802004

  • 相关阅读:
    poj 2488 DFS
    畅通工程 并查集模版
    KMP 模板
    poj 1426 DFS
    poj 2528 线段数
    poj 3468 线段数 修改区间(点)
    CVPR2012文章阅读(2)A Unified Approach to Salient Object Detection via Low Rank Matrix Recovery
    如何制定目标
    Saliency Map 最新综述
    计算机视觉模式识别重要会议杂志
  • 原文地址:https://www.cnblogs.com/grj001/p/12222983.html
Copyright © 2011-2022 走看看