赞
踩
1.创建一个高阶函数来判断token是否存在
- import { Navigate } from 'react-router-dom'
- import { getToken } from '../utile/index'
-
- function AuthComponent({ children }) {
- const isToken = getToken()
- if (isToken) {
- return <>{children}</>
- } else {
- return <Navigate to='/login' replace />
- }
- }
- export { AuthComponent }
2.封装本地存储token
- / 封装locaStrot存取token
- // 设置key属性
- const key = 'pc-key'
-
- // 存token
- const setToken = (token) => {
- return window.localStorage.setItem(key, token)
- }
- // 取token
- const getToken = () => {
- return window.localStorage.getItem(key)
- }
- // 清除token
- const removeToken = () => {
- return window.localStorage.removeItem(key)
- }
-
- export { setToken, getToken, removeToken }
3.在封装的axios请求拦截器中添加token,
- 请求拦截器
- http.interceptors.request.use((config) => {
-
- // 请求拦截器注入token
- const token = getToken()
- if (token) {
- config.headers.Authorization = `Bearer ${token}`
- }
- return config
- }, (error) => {
- return Promise.reject(error)
- })
4.创建mobx 文件:
- import LoginStore from './login.Store.js'
- import React from 'react'
-
- class RootStore {
- constructor() {
- this.loginStore = new LoginStore()
- }
- }
- const rootStore = new RootStore()
- const context = React.createContext(rootStore)
- const useStore = () => React.useContext(context)
- export { useStore }
5.然后再mobx中获取后台数据并赋值变量和存储本地token
- import { http } from '../utile/index'
- import { makeAutoObservable } from 'mobx'
- import { setToken } from '../utile/index.jsx'
-
- class LoginStore {//刷新页面token不会丢失
- token = 'a35cc861-2822-4a9b-a35f-b27fbc1651d2'
- constructor() {
- makeAutoObservable(this)
- }
- setToken = async ({ mobile, code }) => {
- // 调用登录接口
- const res = await http.post('http://geek.itheima.net/v1_0/authorizations', { mobile, code })
- // 获取的后台数据赋值给token
- this.token = res.data.data
- // 把token存到本地存储并传入参数
- setToken(this.token)
-
- }
-
- }
- export default LoginStore
6.在app.js中导入高阶函索判断首页中是否有token,如果有就正常跳转页面,如果没有就跳转到登录页login
- import './App.css';
- import { BrowserRouter, Routes, Route } from 'react-router-dom'
- import Layout from './pages/Layout'
- import Login from './pages/Login'
- // 导入token判断的高阶函数
- import { AuthComponent } from './component/AuthComponent'
-
- function App() {
- return (
- <div className="App">
-
- <BrowserRouter>
- <Routes>
- {/* 这个是需要判断token是否存在 */}
- <Route path='/' element={<AuthComponent><Layout /></AuthComponent>}></Route>
- <Route path='/login' element={<Login />}></Route>
- </Routes>
- </BrowserRouter>
- </div>
- );
- }
-
- export default App;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。