Set token local cache in vue

王林
Release: 2023-05-11 11:16:06
Original
1266 people have browsed it

In front-end development, user identity verification is often required to ensure the user's legitimacy and security. Token authentication has become an increasingly common method. It allows users to log in and do not need to enter their account and password again for verification in subsequent visits. They only need to pass the Token. There are often such requirements in Vue applications. For example, a Token is required to access protected resources when sending a request, or Token verification is required when routing guards are performed on some pages that require login to enter. So how to set up the local cache of Token in Vue?

This article will introduce how to use localStorage in Vue to cache Token locally so that Token can remain valid for a certain period of time after the user refreshes the page or closes the browser.

What is localStorage?

localStorage is a newly added feature in HTML5. It can store data locally on the client and has the following advantages:

  1. Compared with Cookie, localStorage stores The data volume is larger and can store about 5MB of data;
  2. The data stored in localStorage will not be sent to the server with the request, which helps save request bandwidth and improve application performance;
  3. You can use localStorage to implement simple addition, deletion, modification and query operations on data locally on the client.

Use localStorage in Vue for Token local caching

In Vue applications, we usually need to store the user's Token value locally on the client after logging in, so that when the user opens You can still stay logged in when you create a new page or refresh the page without having to authenticate again.

The following is a sample code for using localStorage to cache Token in Vue:

// 存储 Token
localStorage.setItem('token', 'xxxxxxxxxx');

// 获取 Token
let token = localStorage.getItem('token');

// 删除 Token
localStorage.removeItem('token');
Copy after login

Among them, the setItem method of localStorage can be used to store the Token value locally on the client, and the getItem method can be used to obtain the Token. value, the removeItem method can delete the stored Token value locally.

Therefore, in Vue applications, we usually need to store the Token value returned by the server into localStorage after the user logs in. In subsequent requests, as long as the Token is read from localStorage, you can continue. Use previous identity authentication information to successfully pass identity authentication.

The following is a sample code that uses axios interceptor localStorage for Token verification:

// 实例化 axios 对象
const axiosInstance = axios.create({
    baseURL: 'https://api.example.com'
});

// 添加 request 拦截器
axiosInstance.interceptors.request.use((config) => {
    // 从 localStorage 中获取 Token
    let token = localStorage.getItem('token');

    // 配置请求头包含 Token
    if (token) {
        config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
}, (error) => {
    return Promise.reject(error);
});

// 添加 response 拦截器
axiosInstance.interceptors.response.use((response) => {
    if (response.data.code === '401') {
        // 如果返回的状态码为 401(未授权),则从 localStorage 中删除 Token,并跳转到登录页面重新认证
        localStorage.removeItem('token');
        router.push({name: 'login'});
    }

    return response;
}, (error) => {
    return Promise.reject(error);
});

export default axiosInstance;
Copy after login

In this sample code, add a request interceptor through axios.interceptors.request before sending the request Read the Token value from localStorage and add the Token to the request header, so that the user currently requesting access can be identified during identity authentication in the background. In the response interceptor, if the returned status code is unauthorized, the Token value is deleted from localStorage and jumps to the login page for re-authentication.

Summary

Using Token authentication has become a common method in front-end development, and using localStorage for Token caching is also often used. In Vue, we can easily use localStorage to store, obtain and delete Token. It is worth noting that when using localStorage for local caching, you need to follow the principles of client security to prevent the leakage of sensitive data, such as encrypting the Token and only passing encrypted data, etc.

The above is the detailed content of Set token local cache in vue. For more information, please follow other related articles on the PHP Chinese website!

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!