在某些情况下,有时候会在接口请求的API中需要拿到存在浏览器中的COOKIE,调用的方式可以为:
// 获取浏览器Cookie function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0; i <ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; }
在axios请求中,需要在发送前和发送后进行简单的设置拦截:
// 添加一个响应拦截器 Axios.interceptors.request.use((config) => { let account = sessionStorage.account; let token = sessionStorage.token; // if(config.url == Axios.bullRanking){ // // config.headers['Authorization'] = 'Bearer'; // }else{ // config.headers['Authorization'] = 'Bearer ' + token; // } config.headers['Authorization'] = 'Bearer ' + token // config.headers['Accept'] = 'application/json' // config.headers['account'] = account; //在发送请求之前做某件事 // 判断是否登录 // let cur_id = "cur_id", // sign = "sign"; // if (!cur_id||!sign) { // localStorage.clear(); // window.location.href = "index.html"; // }; // 给手机验证码接口加mcode // if(config.url == Axios.send_sms){ // if(sessionStorage.mcode){ // var mcode = sessionStorage.mcode // config.data.mcode = mcode // } // } if(config.url) if(config.method === 'post'){ config.data = qs.stringify(config.data); config.data = config.data+"&account=" + account; config.headers['locale'] = getCookie('language')=='Chinese'?'zh-CN':'en'; config.headers['from'] = 'pc'; } if(config.method === 'get'){ config.headers['locale'] = getCookie('language')=='Chinese'?'zh-CN':'en'; config.headers['from'] = 'pc'; } return config; },(error) =>{ _.toast("错误的传参", 'fail'); return Promise.reject(error); }); // 添加返回信息验证 Axios.interceptors.response.use(function (response) { if(response.data.status =='505' || response.data.status =='404'){ if(!sessionStorage.account){ return false; } sessionStorage.clear(); if (process.env.NODE_ENV === 'production') { window.location.href = "/wap/#/login"; } else { window.location.href = "/#/login"; } } // console.log(sessionStorage.account) if(response.data.status =='401' || response.data.code =='401'){ Vue.prototype.resetSetItem('watchStorage', 'false'); // sessionStorage.setItem("watchStorage", 'false'); // console.log(123) if(window.location.hash !='#/home'&&window.location.hash !='#/XXXX'){ Message({ showClose: true, message: response.data.msg, type: "error" }); window.location.href = "#/Login"; return } } return response; }, function (error) { return Promise.reject(error); });
其中的
Vue.prototype.resetSetItem('watchStorage', 'false');是全局封装的监听sessionStorage变化的。