React或Vue的token持久化

1.新建一个API文件夹,下面新增一个token.js文件,内容如下

//定义key值
const key = 'pc-key'
//存token
const storeToken = (token) => {
  return window.localStorage.setItem(key,token)
}
//取token
const getToken  = () => {
  return window.localStorage.getItem(key)
}
//清空token
const removeToken = () => {
  return window.localStorage.removeItem(key)
}
//导出
export {
  storeToken, getToken, removeToken
}

2.在https中统一管理

import {http} from './request.js'

import { storeToken, getToken, removeToken } from './token'

export { http, storeToken, getToken, removeToken }

3.封装的API如下

import axios from "axios";
import nprogress from "nprogress";
import 'nprogress/nprogress.css'
import { history } from "./history";

import { getToken } from "./token";

const baseURL = 'http://geek.itheima.net/v1_0';

const http = axios.create({
  // 基础地址
  baseURL,
  // 默认超时的时间
  timeout: 5000
})

// 请求拦截

http.interceptors.request.use(config => {
  //这里是获取token值
  const token = getToken()
  if(token) {
    //获取token
    config.headers.Authorization = `Bearer ${token}`
  }
  nprogress.start();
  return config;
}, err => {
  // 打印错误值
  return Promise.reject(err)
})

// 响应拦截
http.interceptors.response.use(
  res => {
    nprogress.done();
    return res.data
  },
  error => {
    if (error.response.status === 401) {
      history.push('/login')
    }
      return Promise.reject(error.response)
    }
  
)

// 整体导出
export { http }

4.在Mobx页面使用

  1. 拿到token的时候一式两份,存本地一份
  2. 初始化的时候优先从本地取,取不到再初始化为控制
import { makeAutoObservable } from "mobx";
import { http, storeToken, getToken,removeToken } from "../API";

class Login{
  //去拿token,如果没有,那就赋值为空 实现持续化token的关键
  token = getToken() || ''
  constructor() {
    makeAutoObservable(this)
  }
  setToken = async ({mobile,code}) => {
    const {data:res} = await http.post('/authorizations',{
      mobile,code
    })

    this.token = res.token
    // 存token
    storeToken(this.token)
  }
  loginOut = () => {
    this.token = ''
    removeToken()
  }
}
export default Login

你可能感兴趣的:(react,token持久化,react.js,封装)