首页 > 解决方案 > 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>
    )
}

标签: javascriptreactjsauthentication

解决方案


推荐阅读