一、概述

从后端获取 token 后,需要先用 store 进行存储,然后给 axios 加上 store 里存储的 token

二、步骤

2.1 新建 index.js

src 目录中新建 store 文件夹,然后新建 index.js 文件。

  1. import { createStore } from 'vuex'
  2. const store = createStore({
  3. state: {
  4. // 存储 token
  5. Authorization: localStorage.getItem('Authorization') ?localStorage.getItem('Authorization') : ''
  6. },
  7. mutations: {
  8. changeLogin (state, user) {
  9. state.Authorization = user.Authorization;
  10. localStorage.setItem('Authorization', user.Authorization);
  11. }
  12. }
  13. })
  14. export default store;

2.2 调用 changeLogin 存储 token

Login.vue 或者其他登录页面中先引入import store from '@/store/index',然后在后端给的响应数据中获取 token,之后再调用 commit 执行 changeLogin 函数。
我这边登录成功,后端返回的json 数据:

  1. {
  2. "msg": "登录成功",
  3. "loginResult": true,
  4. "user": {
  5. "id": 1,
  6. "username": "admin",
  7. "password": "yunhu0"
  8. },
  9. "token": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MTY1NDc0NTcxNH0.fmQX5kRcrrg-6CCNqRkkpUCirXUO0yD86yZSeW6z51X-S1f7gZVne53lzzj47pwf_TwbGI3PGparTjKSUBVQCg"
  10. }

接下来主要就是要拿到后端给的 token 值。

  1. // axios 请求登录成功的响应数据
  2. receiverLoginRes.value = JSON.parse(JSON.stringify(res.data));
  3. if (receiverLoginRes.value != null) {
  4. ElMessage.success("登录成功");
  5. // 获取后端给的 token 值
  6. store.commit('changeLogin',{ Authorization: receiverLoginRes.value['token']});
  7. }

2.3 axios 配置

src目录中新建 http.js 文件,使用 axios.interceptors.request.use 对每一个请求进行拦截。

  1. import axios from 'axios'
  2. import store from '@/store/index'
  3. /**
  4. * 请求拦截
  5. */
  6. axios.interceptors.request.use(
  7. config => {
  8. if (store.state.Authorization != null && store.state.Authorization != "") {
  9. // 请求头的 Authorization 加上 token 数据
  10. config.headers.Authorization = store.state.Authorization;
  11. }else {
  12. console.log('no token');
  13. }
  14. return config;
  15. },
  16. error => {
  17. console.log('error in request');
  18. return Promise.reject(error);
  19. }
  20. );
  21. // 导出给 main.js 挂载
  22. export default axios;

main.js 挂载 axios

  1. import { createApp } from 'vue'
  2. import axios from './http'
  3. const app = createApp(App)
  4. app.config.globalProperties.$axios = axios

2.4 查看请求表头

  1. Accept: application/json, text/plain, */*
  2. Accept-Encoding: gzip, deflate, br
  3. Accept-Language: zh-CN,zh;q=0.9
  4. Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MTY1NDc0NTcxNH0.fmQX5kRcrrg-6CCNqRkkpUCirXUO0yD86yZSeW6z51X-S1f7gZVne53lzzj47pwf_TwbGI3PGparTjKSUBVQCg

Authorization中已经带有后端给的 token 值,后端拦截器对这个token 值验证通过后,就可以响应请求。