关于前端vue项目设置请求头权限问题

新建一个公共js文件。如: lp.js.

//设置请求消息头
export function headers(contentType,token){
let headers={};
headers['Content-Type'] = contentType ? contentType : 'application/json;charset=utf-8';
  let a = window.location.href;
  let b = a.indexOf("#");
  let loginUrl = a.substring(b+2);
  if(loginUrl){
    localStorage.loginUrl = loginUrl;
  }
  let url = a.substring(0,b+2);
  if(loginUrl==='login' || loginUrl==='reg' || loginUrl==='phoneAuth' || loginUrl=='emailInfo'){
  	token='';
  }else{
   token=window.localStorage.getItem('jingjing_login_token');
  }
  token = token ? token : '';

let key = 'jmjbGEWO4EyItpA4';
let current_timestamp = new Date().getTime() + '';
let nonce_str = getNonceStr(32);

let lp_sign = sign(token, current_timestamp, nonce_str, key);
headers['token'] = token;
headers['current-timestamp'] = current_timestamp;
headers['nonce-str'] = nonce_str;
headers['lp-sign'] = lp_sign;
return headers;            
}
//生成随机字符串
export function getNonceStr(len) {
    len = len || 32;
    let chars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let maxPos = chars.length;
    let s = '';
    for (let i = 0; i < len; i++) {
        s += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return s;
}



//  在组件中使用直接引用,
import {headers} from '@/assets/js/common/lp.js'

  methods: {
       // 获取员工架构
      getTree() {
        // that.$emit('updataTree')
        let that = this
        this.$http({
	  			method:"get",
	  			url:api.treeList,
	  			**headers:headers('application/json;charset=utf-8'),**
	  			cache:false
	  		}).then(function(res){
	  			if(res.data.code==10000 || res.data.data==null){
            that.treeDatas = res.data.data
            console.log(that.treeDatas,'<//====treeDatas')
	  			}else{
	  			that.$message.error(res.data.msg);
	  			}
        });
      },
   }   

其中api.js中这么定义
 let Butterfly="http://192.168.6.207:8891/jersey/";//xxip

const api = {
  baseUrl:Butterfly,
  treeList:Butterfly+'enterpriseInfo/current/user',
  };
export default api;


当然在路由请求时需要设置,在router.js文件中
router.beforeEach((to, from, next) => {
	if(!localStorage.jingjing_login_token && to.path!=='/' && to.name !== 'phoneAuth' && to.name !== 'reg' && to.name !== 'agree'  && to.name !== 'restPsd' && to.name !== 'ablityAssessment' && to.name !== 'leaveAssessment' && to.name !== 'contact' && to.name !== 'wasAsked' && to.name !== 'newWitesite_index' && to.name !== 'bySinging' && to.name !== 'brokenQuery' && to.name !== 'login'){
     router.push({path:'/login'});
	}else{
	    let a = window.location.href;
        let b = a.indexOf("#");
	    let loginUrl = a.substring(b+2);
	    if(loginUrl){
	      localStorage.loginUrl = loginUrl;
	    }
	   next();
	}
});
export default router;
Logo

前往低代码交流专区

更多推荐