用了很长时间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>