Home  >  Article  >  Web Front-end  >  What is the usage of token in vue

What is the usage of token in vue

藏色散人
藏色散人Original
2023-01-29 10:31:332751browse

Token in vue is a string of strings generated on the server side, used as a token for client requests; its usage methods are as follows: 1. Encapsulate the method of operating local storage local storage; 2. In the encapsulation After the storage is ready, mount it into the global component; 3. Put "token" in "request.js"; 4. Set the routing guard in "index.vue" under the router.

What is the usage of token in vue

The operating environment of this tutorial: Windows 10 system, vue3 version, DELL G3 computer

What is the usage of token in vue? How to use token in Vue

##1. Understand usage
1. Understand (session, cookie) token Introduction of Token: Token is when the client frequently requests data from the server, and the server frequently goes to the database to query the user name and password and compare them to determine the user name and password. Correct or not, and give corresponding prompts. In this context, Token came into being.
token is a string of characters generated on the server side as a token for client requests. If the front end uses the username/password to request authentication from the server, and the server authentication is successful, the server will return a Token to the front end. The front end can bring Token with each request to prove its legal status. If this Token is persisted on the server side (such as stored in a database), it is a permanent identity token (unless a validity period is set).

2.Token advantages Token is completely managed by the application, so it can avoid the same origin policy
Token can avoid CSRF attacks
Token can be stateless , can be shared among multiple services
Reduce the pressure on the server, reduce frequent database queries, and make the server more robust.
1. When logging in for the first time, the front end adjusts the login interface of the back end and sends the user name and password

2. The back end receives the request and verifies the user name and password. If the verification is successful, it returns a token

3.

The front end gets the token, stores the token in localStorage and vuex, and jumps to the routing page

4. Every time the front end jumps to the routing page, it

Judge whether there is a token in localStroage, if not, it will jump to the login page, if there is, it will jump to the corresponding routing page

5. Every time you adjust the backend interface, it must be included in the request header. Add token

6. The backend determines whether there is a token in the request header. If there is a token, it will get the token and verify the token. If the verification is successful, the data will be returned. If the verification fails (for example: the token expires), 401 will be returned. The request If there is no token in the header, 401

will be returned. 7. If the front-end gets the status code as 401, it will clear the token information and jump to the login page

2. Actual use
1.Method of encapsulating a local cache Create a new storage folder under src, and create a new index.vue
in the folder. The code is as follows:

// 封装操作localstorage本地存储的方法  模块化

var storage = {
  set(key, value) {
    localStorage.setItem(key, JSON.stringify(value))
  },
  get(key) {
    return localStorage.getItem(key) != 'undefined' ? JSON.parse(localStorage.getItem(key)) : undefined  },
  getForIndex(index) {
    return localStorage.key(index)
  },
  getKeys() {
    let items = this.getAll()
    let keys = []
    for (let index = 0; index < items.length; index++) {
      keys.push(items[index].key)
    }
    return keys  },
  getLength() {
    return localStorage.length  },
  getSupport() {
    return (typeof (Storage) !== &#39;undefined&#39;)
  },
  remove(key) {
    localStorage.removeItem(key)
  },
  removeAll() {
    localStorage.clear()
  },
  getAll() {
    let len = localStorage.length // 获取长度    let arr = new Array(len) // 定义数据集    for (var i = 0; i < len; i++) {
      // 获取key 索引从0开始
      var getKey = localStorage.key(i)
      // 获取key对应的值
      var getVal = localStorage.getItem(getKey)
      // 放进数组
      arr[i] = {
        &#39;key&#39;: getKey,        &#39;val&#39;: getVal      }
    }
    return arr  }}export default storage

2. After encapsulating the storage, mount it into the global component Open main.js under src
and add a code:

Vue.prototype.$storage = storage;

3. Put token in request.js As for what request is, you can refer to another document for details: "How Vue successfully calls a dynamic data interface to solve cross-domain problems":
Click on this document link to jump Method 2 specifically describes request.js

Before each jump route, determine whether there is a token in localStroage (or vuex), or whether it has expired (It can be written in the request interceptor that encapsulates Axios or in the routing guard of the router)

The request.js code is as follows

import axios from &#39;axios&#39;import storage from &#39;@/storage&#39;import router from &#39;@/router&#39;// create an axios instance
const service = axios.create({
  baseURL: &#39;/api&#39;, // url = base url + request url
  timeout: 5000 // request timeout})// 添加请求拦截器,若token存在则在请求头中加token,不存在也继续请求
service.interceptors.request.use(
  config => {
    // 每次发送请求之前检测都vuex存有token,那么都要放在请求头发送给服务器,没有则不带token
    // Authorization是必须的    let tokenInfo = storage.get('TOKEN')
    const token = tokenInfo ? tokenInfo.accessToken : null
    const tokenType = token ? tokenInfo.tokenType.substring(0, 1).toUpperCase() + tokenInfo.tokenType.substring(1) + ' ' : null    if (token && tokenType) {
      config.headers.Authorization = tokenType + token    }
    return config  },
  error => {
    console.log('在request拦截器检查到错误:', error.response)
    return Promise.reject(error)
  })// respone拦截器
service.interceptors.response.use(
  response => {
    return response  },
  error => {
    // 在status不正确的情况下,判别status状态码给出对应响应    if (error.response) {
      console.log('在respone拦截器检查到错误:')
      switch (error.response.status) {
        case 204:
          error.response.data.error = '204:No Content(没有内容)'
          break
        case 401:
          // 可能是token过期,清除它
          storage.remove('tokenInfo')
          location.reload() // 刷新页面,触发路由守卫
          error.response.data.error = '401:Unauthorized(未经授权)'
          break
        case 403:
          error.response.data.error = '403:Forbidden(被禁止的)'
          break
        case 500:
          error.response.data.error = '500:服务器内部错误'
          break
        default:          return error      }
      return Promise.reject(error.response.data.error)
    }

    return Promise.reject(error)
  })export default service

4. Set the routing in index.vue under routing and router Guard The entire index code is as follows:

import Vue from 'vue'import Router from 'vue-router'import Login from '@/views/login';import Main from '@/main/index';import tip1 from '@/views/tip1';import tip2 from '@/views/tip2';import tip3 from '@/views/tip3';import storage from '@/storage'Vue.use(Router)const routes = [{
    path: '/',
    name: 'Login',
    // redirect: '/login',
    component: Login,  },  {
    path: "/login",
    component: Login,  },  {
    path: '/Main',
    component: Main,
    children: [{
        path: '/',
        name: 'Tip1',
        component: tip1      },      {
        path: '/tip1',
        name: 'Tip1',
        component: tip1      },      {
        path: '/tip2',
        name: 'Tip2',
        component: tip2,
        meta: {
          requireAuth: true
        }
      },      {
        path: '/tip3',
        name: 'Tip3',
        component: tip3      },    ]
  }]const router = new Router({
  routes})// 设置路由守卫,在进页面之前,判断有token,才进入页面,否则返回登录页面
router.beforeEach((to, from, next) => {
  // 默认requiresAuth为false才不需要登录,其他都要
  // to.matched.some(r => r.meta.requireAuth) or to.meta.requiresAuth  if (to.matched.some(r => r.meta.requireAuth) !== false) {
    let tokenInfo = storage.get('TOKEN')
    if (tokenInfo) {
      console.log("有token")
      next();

    } else {
      storage.remove('TOKEN')
      next({
        path: "/login",
        query: {
          redirect: to.fullPath        } // 将刚刚要去的路由path(却无权限)作为参数,方便登录成功后直接跳转到该路由      });
    }

  } else {
    next(); //如果无需token,那么随它去吧  }});//暴露router实例export default router
// 1.将调用登录接口成功以后,把后端传过来的token放入本地缓存
// 2.路由跳转之前执行路由守卫,实例化一个Router对象,使用该对象内置方法beforeEach,在路由跳转前判断该页面是否设置了token,获取token
// 如果有token,next()继续执行路由跳转
// 如果没有token,跳转去登录界面
Which page needs routing guard. Just add parameters to him

meta: {
          requireAuth: true
        }
recommends learning: "vue video tutorial"

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

Statement:
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