vue-resource拦截器实现token发送及检验自动化

用了很长时间vue-resource,最近思考$http发送请求时,如何自动上传token、自动处理token非法时页面跳转时,才发现vue-resource竟然有拦截器(interceptors)机制,可以完美地解决这个问题。
代码很简单,不做过多解释。

<!DOCTYPE html>  
<!--   
vue-resource拦截器测试页面  
http://wallimn.iteye.com  
 -->  
<html>  
<head>  
    <meta charset="utf-8">  
    <meta http-equiv="X-UA-Compatible" content="IE=edge">  
    <meta name="viewport" content="width=device-width, initial-scale=1">  
    <title>vue-resource.interceptors</title>  
</head>  
<body class="main">  
  
<div id="app">  
  
  
</div>  
   
   
   
   
    <script type="text/javascript" src="../res/lib/vue.js"></script>  
    <script type="text/javascript" src="../res/lib/vue-resource.js"></script>  
  
    <script type="text/javascript">  
        //拦截器使用示例  
        //注册拦截器  
        Vue.http.interceptors.push(function(request, next) {  
            var token = sessionStorage.getItem('token');  
            if(token){  
                //不知是Bearer;还是Bearer半角空格,网上两种写法都有。  
                request.headers.set('Authorization','Bearer;' + token);  
                //下面这个方法不正确。浏览器控制台或后台服务程序均无法看到传递值  
                //request.headers.Authorization = 'Bearer;' + token;  
            }  
            console.log("拦截器输出,请求参数:",request.body?request.body:request.params);  
            next(function(response){  
                console.log("拦截器输出,返回状态:",response.status);  
                if (response.status === 401) {  
                    window.location.href = '../public/login.html';  
                }  
            });  
        });  
          
        // Vue实例化  
        var doit = new Vue({  
            el:'#app',  
            data: {},  
            methods: {  
                //测试拦截器,服务正常响应  
                testinterceptors: function(){  
                    this.$http.get("../api/02/test/version").then(function(res){  
                        ;  
                    });  
                },  
                //测试发生异常页面跳转,后台服务抛出异常  
                testexception: function(){  
                    this.$http.get("../api/02/test/exception").then(function(res){  
                        ;  
                    });  
                }  
            }             
        });  
          
        doit.testinterceptors();  
   
    </script>  
      
      
      
</body>  
</html> 
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容