This time I will bring you a detailed explanation of the steps for the vue interceptor to achieve a unified token and be compatible with IE9. What are the precautions for the vue interceptor to implement a unified token and be compatible with IE9? The following is a practical case, let's take a look. one time.
In the project, vue is used to build the front-end page, and the back-end API interface is requested through axios to complete data interaction. If the verification password token is written in each interface, it will be a lot of manual work and not flexible. Here we share the use of vue's built-in interceptor to add a token to the header of each request, and it is compatible with IE9.import axios from 'axios'; // 这里的config包含每次请求的内容,在这里把token放到请求头 axios.interceptors.request.use(function (config) { let token = window.localStorage.getItem("tokenid"); //从缓存中取token if (token) { config.headers.Authorization = token; //将token放到请求头发送给服务器 //这里主要是为了兼容IE9 var browser = navigator.appName; var b_version = navigator.appVersion; if (browser == 'Netscape' && b_version.indexOf(';') < 0) { //火狐 } else { if (b_version.indexOf(';') < 0) { return config; } var version = b_version.split(";"); var trim_Version = version[1].replace(/[ ]/g, ""); if (browser == "Microsoft Internet Explorer" && trim_Version == "MSIE9.0") { //IE9 if (config.url.indexOf('?') > 0) { config.url = config.url + "&token=" + JSON.parse(token).value; } else { config.url = config.url + "?token=" + JSON.parse(token).value; } } } } else { localStorage.clear(); //清空缓存 if (router.currentRoute.name && router.currentRoute.name.toLowerCase() == "login") { //这里需要排除登陆(或者说是第一次请求获取token)的时候的请求验证,我这里没做处理 //我的后台api接口,并没有对login接口做token验证,所以这里不做处理 } else { //除登陆接口外,其他需要token验证的方法,会走这里且返回null return null; } } return config; }, function (err) { // return Promise.reject(err); }); // http response 拦截器 axios.interceptors.response.use( response => { return response; //请求成功的时候返回的data }, error => { try { if (error.response) { switch (error.response.status) { case 401://token过期,清除token并跳转到登录页面 localStorage.clear(); var baurl = window.location.href; router.replace({ path: 'login', query: { backUrl: baurl } }); return; } } return Promise.reject(error.response.data) } catch (e) { } });
vue jquery Lodash sliding top floating fixed function implementation details
The above is the detailed content of Detailed explanation of the steps for Vue interceptor to implement unified token and be compatible with IE9. For more information, please follow other related articles on the PHP Chinese website!