使用vue-resource interceptors拦截器获取token


思路是登录时 记录了token 和 有效的时间


访问接口时 自动判断是否过有效期 并重新获取token


Vue.http.interceptors.push(function(request, next) {
  var date = localStorage.getTokenDate;
  if(request.url.indexOf('/oauth/token')==-1&&new Date().getTime() - new Date(date).getTime()>localStorage.expires_in*1000){
  	  console.info("getToken");
  	  var __url = window.location.protocol + '//13890999:secret@'+ window.location.host + '/oauth/token';
	  var __options=[Vue.http.options.emulateJSON = true];
	  vm.$http.post(__url,{username:_getLoginInfo().username,password:_getLoginInfo().password},__options)
	  .then(function(response){
		  _setLoginInfo(localStorage.currentUser,response.data.access_token,response.data.expires_in)
		  request.headers.set('Authorization', 'Bearer '+ response.data.access_token);
		  next();
	  },function(){
		  top.location='login?t='+Math.random();
	  });
  }else{
	  console.info(new Date().getTime() - new Date(date).getTime());
	  if(request.url.indexOf('/oauth/token')==-1)
		  request.headers.set('Authorization', 'Bearer '+ _getAccessToken());
	  next();
  }


你可能感兴趣的:(vue.js)