一、概述
从后端获取 token 后,需要先用 store 进行存储,然后给 axios 加上 store 里存储的 token。
二、步骤
2.1 新建 index.js
在 src 目录中新建 store 文件夹,然后新建 index.js 文件。
import { createStore } from 'vuex'const store = createStore({state: {// 存储 tokenAuthorization: localStorage.getItem('Authorization') ?localStorage.getItem('Authorization') : ''},mutations: {changeLogin (state, user) {state.Authorization = user.Authorization;localStorage.setItem('Authorization', user.Authorization);}}})export default store;
2.2 调用 changeLogin 存储 token
在 Login.vue 或者其他登录页面中先引入import store from '@/store/index',然后在后端给的响应数据中获取 token,之后再调用 commit 执行 changeLogin 函数。
我这边登录成功,后端返回的json 数据:
{"msg": "登录成功","loginResult": true,"user": {"id": 1,"username": "admin","password": "yunhu0"},"token": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MTY1NDc0NTcxNH0.fmQX5kRcrrg-6CCNqRkkpUCirXUO0yD86yZSeW6z51X-S1f7gZVne53lzzj47pwf_TwbGI3PGparTjKSUBVQCg"}
接下来主要就是要拿到后端给的 token 值。
// axios 请求登录成功的响应数据receiverLoginRes.value = JSON.parse(JSON.stringify(res.data));if (receiverLoginRes.value != null) {ElMessage.success("登录成功");// 获取后端给的 token 值store.commit('changeLogin',{ Authorization: receiverLoginRes.value['token']});}
2.3 axios 配置
在 src目录中新建 http.js 文件,使用 axios.interceptors.request.use 对每一个请求进行拦截。
import axios from 'axios'import store from '@/store/index'/*** 请求拦截*/axios.interceptors.request.use(config => {if (store.state.Authorization != null && store.state.Authorization != "") {// 请求头的 Authorization 加上 token 数据config.headers.Authorization = store.state.Authorization;}else {console.log('no token');}return config;},error => {console.log('error in request');return Promise.reject(error);});// 导出给 main.js 挂载export default axios;
main.js 挂载 axios。
import { createApp } from 'vue'import axios from './http'const app = createApp(App)app.config.globalProperties.$axios = axios
2.4 查看请求表头
Accept: application/json, text/plain, */*Accept-Encoding: gzip, deflate, brAccept-Language: zh-CN,zh;q=0.9Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MTY1NDc0NTcxNH0.fmQX5kRcrrg-6CCNqRkkpUCirXUO0yD86yZSeW6z51X-S1f7gZVne53lzzj47pwf_TwbGI3PGparTjKSUBVQCg
Authorization中已经带有后端给的 token 值,后端拦截器对这个token 值验证通过后,就可以响应请求。
