Home Web Front-end JS Tutorial Detailed explanation of the steps for Vue interceptor to implement unified token and be compatible with IE9

Detailed explanation of the steps for Vue interceptor to implement unified token and be compatible with IE9

May 15, 2018 am 11:03 AM
ie token compatible

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(&#39;;&#39;) < 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(&#39;?&#39;) > 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:

vue jquery Lodash sliding top floating fixed function implementation details

##jQuery steps to implement the electronic clock function Detailed explanation

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What to do if the login token is invalid What to do if the login token is invalid Sep 14, 2023 am 11:33 AM

Solutions to invalid login token include checking whether the Token has expired, checking whether the Token is correct, checking whether the Token has been tampered with, checking whether the Token matches the user, clearing the cache or cookies, checking the network connection and server status, logging in again or requesting a new Token. Contact technical support or developers, etc. Detailed introduction: 1. Check whether the Token has expired. The login Token usually has a validity period set. Once the validity period exceeds, it will be considered invalid, etc.

How to solve the problem of invalid login token How to solve the problem of invalid login token Sep 14, 2023 am 10:57 AM

The problem of invalid login token can be solved by checking the network connection, checking the token validity period, clearing cache and cookies, checking login status, contacting the application developer and strengthening account security. Detailed introduction: 1. Check the network connection, reconnect to the network or change the network environment; 2. Check the token validity period, obtain a new token, or contact the developer of the application; 3. Clear cache and cookies, clear browser cache and Cookie, and then log in to the application again; 4. Check the login status.

How to solve the problem of storing user tokens in Redis How to solve the problem of storing user tokens in Redis May 31, 2023 am 08:06 AM

Redis stores user tokens. When designing a system similar to e-commerce, a common requirement is that each page needs to carry logged-in user information. There are two common solutions: using cookies to save and using JWT to save. But if Redis cache is used in the system, there is also a third solution - caching the user token in Redis. Generate a token when logging in and store it in Redis //Generate a token object and save it in redis redisTemplate.opsForHash().put("token","user",user)

The most stable version of Win10 The most stable version of Win10 Dec 25, 2023 pm 07:58 PM

Many users will encounter freezes or blue screens when operating the computer. At this time, we need to find the most stable win10 version to operate. Overall, it is very easy to use and can make your daily use smoother. The most stable win10 version in history 1. Win10 genuine original system. Here users can use simple operations. The system has been optimized and has strong stability, security and compatibility. Users can follow the steps to achieve the perfect machine. 2. Russian master streamlined The version of win10 has been strictly streamlined and many unnecessary functions and services have been deleted. After streamlining, the system has lower CPU and memory usage and runs faster. 3. Win10 Lite Edition 1909 is installed on multiple computers with different hardware models.

Internet Explorer opens Edge: How to stop MS Edge redirection Internet Explorer opens Edge: How to stop MS Edge redirection Apr 14, 2023 pm 06:13 PM

It's no secret that Internet Explorer has fallen out of favor for a long time, but with the arrival of Windows 11, reality sets in. Rather than sometimes replacing IE in the future, Edge is now the default browser in Microsoft's latest operating system. For now, you can still enable Internet Explorer in Windows 11. However, IE11 (the latest version) already has an official retirement date, which is June 15, 2022, and the clock is ticking. With this in mind, you may have noticed that Internet Explorer sometimes opens Edge, and you may not like it. So why is this happening? exist

What should I do if win11 cannot use ie11 browser? (win11 cannot use IE browser) What should I do if win11 cannot use ie11 browser? (win11 cannot use IE browser) Feb 10, 2024 am 10:30 AM

More and more users are starting to upgrade the win11 system. Since each user has different usage habits, many users are still using the ie11 browser. So what should I do if the win11 system cannot use the ie browser? Does windows11 still support ie11? Let’s take a look at the solution. Solution to the problem that win11 cannot use the ie11 browser 1. First, right-click the start menu and select "Command Prompt (Administrator)" to open it. 2. After opening, directly enter "Netshwinsockreset" and press Enter to confirm. 3. After confirmation, enter "netshadvfirewallreset&rdqu

How Vue3+Vite uses dual tokens to achieve senseless refresh How Vue3+Vite uses dual tokens to achieve senseless refresh May 10, 2023 pm 01:10 PM

1. Token login authentication jwt: JSONWebToken. It is an authentication protocol that is generally used to verify the requested identity information and identity permissions. Composed of three parts: Header, Hayload, Signatureheader: that is, the header information, which is the basic information describing this token, json format {"alg":"HS256", //indicates the signature algorithm, the default is HMACSHA256 (written as HS256) "type":"JWT"//Indicates the type of Token. JWT tokens are uniformly written as JWT}pa

How to solve C++ syntax error: 'expected primary-expression before ':' token'? How to solve C++ syntax error: 'expected primary-expression before ':' token'? Aug 26, 2023 pm 04:06 PM

How to solve C++ syntax error: 'expectedprimary-expressionbefore':'token'? Syntax errors are a common problem in C++ programming. One of the common errors is the "expectedprimary-expressionbefore':'token" error message. This error usually occurs when using conditional expressions and the ternary operator. This article will introduce the cause of this error

See all articles