vue interceptor compatibility processing

php中世界最好的语言
Release: 2018-06-04 15:15:48
Original
1975 people have browsed it

This time I will bring you the vue interceptor compatibility process. What are the precautions when using the vue interceptor compatibility? The following is a practical case, let's take a look.

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) {
    }
  });
Copy after login

Write it at the back. Because my token is placed in the cache, before each request, I will first take out the token on the front end and verify its timeliness. If it expires or does not exist, I will jump to the login page first without going through the interceptor. Go request request. Please also refer to the mounted() method for details.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of utils.js use cases

How to use Vue to operate DIV

The above is the detailed content of vue interceptor compatibility processing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!