1.修改request.js 加在请求中。一般都是加在header中,后台处理用 加在哪看后台要求
export default class RequestTools { /* * data 接口传参数据 * urlStr 接口地址名称 * post请求 */ axiosPost = (data, urlStr) => { data.token = localStorage.getItem('token') return server({ url: url[urlStr], method: 'post', dataType: "json", data: data, }) } }
修改server.js 加在header中
//开始请求设置,发起拦截处理 axios.interceptors.request.use( config => { //RequestPayload格式转FormData config.headers['token'] = localStorage.getItem('token') config.headers['content-type'] = 'application/x-www-form-urlencoded' config.data = qs.stringify(config.data) return config }, err => { return err } )
修改login.js 返回后写入token,和登录状态
const submit = () => { let params = { username, password } _req.axiosPost(params, 'doUserLogin').then(res => { console.log(res) if (res.code === 0) { message.success(res.data.msg) localStorage.setItem('isLogin',true) localStorage.setItem('token',res.data.token) navigate('/app/home') } }) }
修改router.js 增加登录状态判断,防君子不防小人,后来还是需要再做验证
import React from 'react' import { HashRouter, Routes, Route, Navigate } from 'react-router-dom' import Login from 'pages/login/login' import AppPage from 'pages/app/app' import Home from 'pages/home/home' import ArticleList from 'pages/article/article' function RequireAuth({ children }) { const authed = localStorage.getItem('isLogin') return authed === 'true' ? ( // 判断 localstorage 中登录状态是否为 true children ) : ( <Navigate to="/" replace /> // 跳转到登录 ); } function RouterDom() { return ( <HashRouter> <Routes> <Route path="/" element={<Login/>} /> <Route path="/app/*" element={<RequireAuth><AppPage/></RequireAuth>} > <Route path="home" element={<Home/>} /> <Route path="article" element={<ArticleList/>} /> </Route> </Routes> </HashRouter> ); } export default RouterDom
本文为看恩吧原创文章,转载无需和我联系,但请注明来自knsay.com