当前位置:网站首页>Token processing during API encapsulation

Token processing during API encapsulation

2022-06-22 14:59:00 13 less

1.token What is it? ?

token Like a key , When you click login , Backstage will return a token. You may need to use... When calling other interfaces token.

token Is an encrypted string such as :

 

2. Add... To the request header token

Access to some interfaces , Yes, it needs to be carried token In the past , This time can be in Request interceptor Add inside , At this time, when we request the interface, we will token Carry the past .

import Store from '@/store'

if (Store.state.user.token) {
    config.headers.Authorization = `Bearer ${Store.state.user.token}`
}

3. take token Store in Vuex in

Vuex Refresh data will be lost , This use will use local storage , More plug-ins CookieJs. This solves the problem of missing refresh pages token The problem of .

(1)cookieJs Usage of :

import Cookies from 'js-cookie'

const TokenKey = 'vue_admin_template_token'

export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}

(2) stay store/modules/user.js Under module

//  take token Storage vuex in ,vuex The refresh is gone , Solve the problem of no refresh 
import { getToken, setToken } from '@/utils/auth'
import { sysLogin } from '@/api/login'
import { sysProfile, sysUser } from '@/api/user'
import { Message } from 'element-ui'
// import { sysProfile } from '@/api/user'
const state = {
  //  Take it if you have it token  If not, it will be empty 
  token: getToken() || '',
  userInfo: ''
}
const mutations = {
  setToken(state, value) {
    state.token = value
    setToken(value)
  },
  setUserInfo(state, value) {
    state.userInfo = value
  }
}
const actions = {
  //  Sign in 
  async toLogin(store, form) {
    const res = await sysLogin(form)
    Message.success(' Login successful ')
    store.commit('setToken', res.data)
    console.log(2)
  },
  //  Get user information 
  async getUserInfo({ commit }) {
    const res = await sysProfile()
    console.log(res, ' Basic information of users ')
    //  Get user image 
    const res2 = await sysUser(res.data.userId)
    console.log(res2, ' The avatars ')

    commit('setUserInfo', Object.assign({}, res.data, res2.data))
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
}

4.token Treatment of failure

token There is a duration , This duration is set by the backend , When there is a 401 When token It doesn't work , The user can no longer log in .

This time the user should return to the login page , And get rid of token, And user information .

  (error) => {
    if (error.response && error.response.status === 401) {
      //  eliminate token
      //  Clear user information 
      Store.commit('user/setToken', '')
      Store.commit('user/setUserInfo', '')
      Router.push('/login')
      //  Error message 
      Message.error(error.response.data.message)
      //  Jump to the login page for value transfer 
      Router.push('/login?redirect=' + window.location.href.split('#')[1])
    }
    return Promise.reject(error)
  }

The status code returned by the server is 401, Generally speaking, it is due to insufficient permissions .

Expand your knowledge :

common http Status code :

2xx  The server responded successfully

3xx  Redirect

4xx  Insufficient authority

500  It may be a server error

5. use token Does the user have to log in ?

The answer is not necessarily , Others can also log in to token To forge , But there is one thing the user must have logged in , That is the user's information .

原网站

版权声明
本文为[13 less]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221328044166.html