javascript - React js 中的路由保护无法正常工作
问题描述
我在后端使用 Laravel,在前端使用 react.js,当我尝试登录时,它会重定向到主页(“/”),但是当我刷新页面时,我会再次重定向到登录页面。我正在使用以组件为参数的死记硬背的保护文件,并且在受保护的路由中传递的所有组件只能由登录用户访问。登录后,当我尝试访问受保护的页面时,我被重定向到登录页面。任何正文都可以帮助?
应用程序.js
function App() {
return (
<div className="App">
{/* <AuthContextProvider> */}
<BrowserRouter>
<Switch>
<Route path = "/login"><Login/></Route>
<Route path= "/register"><Register/></Route>
<Route path = "/add"><AuthProtection component = {AddProduct}/> </Route>
<Route path = "/update"><AuthProtection component = {UpdateProduct}/> </Route>
<Route path = "/search"><AuthProtection component = {Search}/> </Route>
<Route path = "/"><AuthProtection component = {Home}/> </Route>
</Switch>
</BrowserRouter>
{/* </AuthContextProvider> */}
</div>
);
}
export default App;
登录.js
export const Login = () => {
const history = useHistory()
const [email, setemail] = React.useState("")
const [password, setpass] = React.useState("")
const loginuser = e =>{
e.preventDefault();
axios.defaults.withCredentials = true;
let data = {email,password}
axios.get('http://localhost:8000/sanctum/csrf-cookie').then(response => {
console.log(response)
axios.post('http://localhost:8000/login',data ,{
headers: {
'Content-Type': 'application/json',
"Accept": "application/json",
'X-XSRF-TOKEN': (() => {
const name = 'XSRF-TOKEN'
const cookies = '; ' + document.cookie
const parts = cookies.split('; ' + name + '=')
const value = parts.length == 2 ? parts.pop().split(';').shift() : null
console.log('>>> XSRF-TOKEN', value)
return value
})(),
},
}).then(response => {
localStorage.setItem("user-info" , JSON.stringify(response.config.headers["X-XSRF-TOKEN"]))
Auth.authenticate();
history.push("/");
});
});
}
return (
<>
<Header/>
<div>
<div className="wrapper fadeInDown">
<div id="formContent">
{/* Tabs Titles */}
{/* Icon */}
<div className="fadeIn first">
</div>
{/* Login Form */}
<form onSubmit = {loginuser}>
<input type="text" value={email} onChange={(e)=>setemail(e.target.value)} className="fadeIn second" placeholder="login" />
<input type="password" value={password} onChange={(e)=>setpass(e.target.value)} className="fadeIn third" placeholder="password" />
<button type="submit" className="fadeIn fourth btn btn-primary" >LOGIN</button>
</form>
{/* Remind Passowrd */}
<div id="formFooter">
<a className="underlineHover" href="#">Forgot Password?</a>
</div>
</div>
</div>
</div>
</>
)
}
Auth.js
const Auth = {
isAuthenticated: false,
authenticate() {
this.isAuthenticated = true;
},
signout() {
this.isAuthenticated = false;
},
getAuth() {
return this.isAuthenticated;
}
};
export default Auth;
protectedRoutes.js
import React from 'react'
import { useHistory } from 'react-router'
import Auth from './Auth'
import { AuthContext } from './AuthContext';
export const AuthProtection = (props) => {
console.log(props)
const history = useHistory()
let ProtectedTemplate = props.component
console.log(Auth.getAuth())
React.useEffect(()=>{
if( !Auth.getAuth() ){
history.push("/login")
}
})
return (
<div>
<ProtectedTemplate/>
</div>
)
}
解决方案
推荐阅读
- pine-script - Q - Pinescript Sweep Indicator - 如何仅在被触摸时才显示线条?
- swiftui - 如何在 SwiftUI 的列表项中调用完成处理程序?
- iis - 将 IIS 服务器设置为使用“Content-Security-Policy”标头
- python - Keras LSTM:从单个输入数组预测多个序列
- python - 点击帮助没有出现
- c# - 有没有更有效的方法从 Monogame C# 中的 Texture2D 创建位图?
- android - Android HLS 流式传输并将视频录制到 android 手机
- angular - 无法在 FormGroupDirective.onSubmit Angular 9 的 syncPendingControls 处读取 null 的属性“_syncPendingControls”
- javascript - 如何根据其位置设置位置:相对父级的高度:绝对子级?
- php - 正则表达式在文本中搜索单词而不是作为字符串的一部分 (preg_match_all)