猿问

使用 JWT 保护 React 上的路由

我正在尝试为我的 React 项目创建受保护的路由,在后端我有 NodeJS。我看了很多例子,他们使用 localStorage 或“fakeAuth”,所以我没有真正获得我需要的正确信息,我遇到的主要问题是,当我登录时,我应该如何保存我登录的信息ATM,这样我的前端部分就可以看到这一点。


在我的 PrivateRoute 组件中,我需要有一个布尔值来描述我的统计信息(是否登录),但我真的不明白我应该如何从我的后端我的 PrivateRoute 组件中“提取”该信息:(布尔值应该在{{??????????????}} 的地方


import React from "react";

import { Route, Redirect } from  "react-router-dom";

import {authentication} from "./login.component"

import axios from 'axios';

export const PrivateRoute = ({ component: Component, ...rest}) => (

    <Route 

        {...rest}

        render={props => 

            {{??????????????}} ? (

                <Component {...props} />

                <Redirect

                    to={{

                        pathname: "/login",

                       state: { from: props.location }

                    }}

                />  

            )

        }

    />

);

这是我的登录组件:


import React, { useState } from 'react';

import axios from 'axios';

const Login = () => {

    const [username, setUsername] = useState('');

    const [password, setPassword] = useState('');

    const onChangeUsername = (e) => {

    setUsername(e.target.value);

    };

    const onChangePassword= (e) => {

     setPassword(e.target.value);

    };

    const onSubmit = async (e) => {

        const user = {

            username: username,

            password: password

            };

        e.preventDefault();

        await axios.post('http://localhost:5000/users/login', user);

    };


也许有人可以帮助我,任何关于如何做到这一点的建议、教程、示例都会有所帮助。


狐的传说
浏览 82回答 1
1回答

牧羊人nacy

大多数教程使用localStorageorcookie是因为您希望即使在用户刷新页面后也保留登录状态,这样他们就不必每次都重新登录。但要回答你的问题,你可以这样做:import React, { useState } from "react";import { Route, Redirect, BrowserRouter } from "react-router-dom";import "./style.css";import axios from "axios";function yourLoginPostApi() {&nbsp; return new Promise(r => setTimeout(() => r(true), 1000));}function Login({ onSuccess }) {&nbsp; const [username, setUsername] = useState("");&nbsp; const [password, setPassword] = useState("");&nbsp; let [loading, setLoading] = useState(false);&nbsp; const onChangeUsername = e => {&nbsp; &nbsp; setUsername(e.target.value);&nbsp; };&nbsp; const onChangePassword = e => {&nbsp; &nbsp; setPassword(e.target.value);&nbsp; };&nbsp; const onSubmit = async e => {&nbsp; &nbsp; const user = {&nbsp; &nbsp; &nbsp; username: username,&nbsp; &nbsp; &nbsp; password: password&nbsp; &nbsp; };&nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; setLoading(true);&nbsp; &nbsp; // Uncomment this line and remove the next one since it's a fake api call&nbsp; &nbsp; // let response = await axios.post("http://localhost:5000/users/login", user);&nbsp; &nbsp; let response = await yourLoginPostApi();&nbsp; &nbsp; setLoading(false);&nbsp; &nbsp; onSuccess(response);&nbsp; };&nbsp; return (&nbsp; &nbsp; <div className="Login">&nbsp; &nbsp; &nbsp; <h2>Traffic scan admin panel</h2>&nbsp; &nbsp; &nbsp; <div className="LoginInfo-Logins">&nbsp; &nbsp; &nbsp; &nbsp; <form>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type="text"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; required&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; className=""&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={username}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChange={onChangeUsername}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; placeholder="Username*"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type="text"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; required&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; className=""&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={password}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChange={onChangePassword}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; placeholder="Password*"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; </form>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; <button onClick={onSubmit}>SIGN IN</button>&nbsp; &nbsp; &nbsp; <div>{loading && "Please wait..."}</div>&nbsp; &nbsp; </div>&nbsp; );}function PrivateRoute({ children }) {&nbsp; let [loggedIn, setLoggedIn] = useState(false);&nbsp; return loggedIn ? (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; {children}&nbsp; &nbsp; &nbsp; <button onClick={() => setLoggedIn(false)}>log out</button>&nbsp; &nbsp; </div>&nbsp; ) : (&nbsp; &nbsp; <Login onSuccess={() => setLoggedIn(true)} />&nbsp; );}export default function App() {&nbsp; return (&nbsp; &nbsp; <BrowserRouter>&nbsp; &nbsp; &nbsp; <PrivateRoute>&nbsp; &nbsp; &nbsp; &nbsp; <div>Stuff only a logged in user should see</div>&nbsp; &nbsp; &nbsp; </PrivateRoute>&nbsp; &nbsp; </BrowserRouter>&nbsp; );}你可以在 stackblitz 上看到演示
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答