当前位置:网站首页>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 .
边栏推荐
- Biden signs two new laws aimed at strengthening government cyber security
- Network address translation nat
- 得物技术复杂 C 端项目的重构实践
- C # paging calculation total pages, current page data set
- At 19:00 this Thursday evening, the 7th live broadcast of battle code Pioneer - how third-party application developers contribute to open source
- 作为程序员,职业规划需要注意的四个阶段
- 一文彻底弄懂建造者模式(Builder)
- MySQL learning notes 2022
- Struggle, programmer -- Chapter 46 this situation can be recalled, but it was at a loss at that time
- C # WinForm photo album function, picture zooming, dragging, preview Pagination
猜你喜欢

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

C # WinForm photo album function, picture zooming, dragging, preview Pagination

Common real machine debugging plug-ins for unity commercial games

轻松上手Fluentd,结合 Rainbond 插件市场,日志收集更快捷

Open source SPL redefines OLAP server

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

数据库连接池:连接池功能点的实现
![[untitled]](/img/ff/f23e5275683d4d7b13fcb94cc77702.png)
[untitled]

C language student management system (open source)

Unity商业游戏常用真机调试插件
随机推荐
大会倒计时 | 亚马逊云科技创新大会邀您一起构建AI新引擎 !
flutter video_player实现监听和自动播放下一首歌曲
口令安全是什么意思?等保2.0政策中口令安全标准条款有哪些?
Open source SPL redefines OLAP server
bochs 软件使用记录
Lisez ceci pour vous apprendre à jouer avec la cible de test de pénétration vulnhub - driftingblues - 5
PHP内置协议(支持的协议和封装协议)
The diffusion model is crazy again! This time the occupied area is
Fluentd is easy to get started. Combined with the rainbow plug-in market, log collection is faster
Biden signs two new laws aimed at strengthening government cyber security
Groovy list operation
[Zhejiang University] information sharing of the first and second postgraduate entrance examinations
看完這篇 教你玩轉滲透測試靶機Vulnhub——DriftingBlues-5
Front and back management system of dessert beverage store based on SSM framework dessert mall cake store [source code + database]
Groovy之闭包
Sikulix select the picture of relative position (advanced version)
推动制造业高效增长,用友U9 cloud不断精进背后的密码
一文彻底弄懂单例模式(Singleton)
开源SPL重新定义OLAP Server
MySQL learning notes 2022