当前位置:网站首页>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 .
边栏推荐
- U++ 迭代 排序 查询 学习笔记
- Struggle, programmer -- Chapter 44: eight hundred miles under one's command, fifty strings turning over the Great Wall
- 『忘了再学』Shell流程控制 — 38、while循环和until循环介绍
- Closure of groovy
- Biden signe deux nouvelles lois visant à renforcer la cybersécurité du Gouvernement
- Fluentd is easy to get started. Combined with the rainbow plug-in market, log collection is faster
- Dessert mall management system based on SSH framework [source code + database]
- Reading of double pointer instrument panel (II) - Identification of dial position
- A thorough understanding of singleton
- RealNetworks vs. Microsoft: the battle in the early streaming media industry
猜你喜欢

树结构二叉树

网络地址转换NAT

NF-ResNet:去掉BN归一化,值得细读的网络信号分析 | ICLR 2021

Verification code is the natural enemy of automation? See how the great God solved it
![[PR] basic process](/img/e6/13a5703cfb8e5c51ed06fe9b0d9485.png)
[PR] basic process

Data collection: skillfully using Bloom filter to extract data summary

PHP built-in protocols (supported and encapsulated protocols)

难怪考研热度这么高,这些是研究生才有的“隐藏福利”!

看完这篇 教你玩转渗透测试靶机Vulnhub——DriftingBlues-5

phpStudy 2016搭建-pikachu靶场
随机推荐
Excuse me, is Zhongyan futures reliable? Is the fund safe?
As a passer-by, some advice for programmers who are new to the workplace
PHP built-in protocols (supported and encapsulated protocols)
CSAPP之详解Labs
flutter video_ Player monitors and automatically plays the next song
What are strong and weak symbols in embedded systems?
山东泰安“6·21”燃气爆炸事故后续:全面排查整治餐饮场所燃气安全隐患
作为过来人,写给初入职场的程序员的一些忠告
Madcap flare 2022, documentation in language or format
No wonder the postgraduate entrance examination is so hot. These are the "hidden benefits" of Postgraduates!
剑指Offer46——把数字翻译成字符串
C # paging calculation total pages, current page data set
同花顺如何开户?在线开户安全么?
RealNetworks vs. Microsoft: the battle in the early streaming media industry
[Software Engineering] planning and project management
本周四晚19:00战码先锋第7期直播丨三方应用开发者如何为开源做贡献
Introduction to groovy syntax
The diffusion model is crazy again! This time the occupied area is
Those confusing user state & kernel state
机器学习之随机森林