第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 JWT 保護 React 上的路由

使用 JWT 保護 React 上的路由

狐的傳說 2023-10-14 18:36:45
我正在嘗試為我的 React 項目創(chuàng)建受保護的路由,在后端我有 NodeJS。我看了很多例子,他們使用 localStorage 或“fakeAuth”,所以我沒有真正獲得我需要的正確信息,我遇到的主要問題是,當我登錄時,我應(yīng)該如何保存我登錄的信息ATM,這樣我的前端部分就可以看到這一點。在我的 PrivateRoute 組件中,我需要有一個布爾值來描述我的統(tǒng)計信息(是否登錄),但我真的不明白我應(yīng)該如何從我的后端我的 PrivateRoute 組件中“提取”該信息:(布爾值應(yīng)該在{{??????????????}} 的地方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);    };也許有人可以幫助我,任何關(guān)于如何做到這一點的建議、教程、示例都會有所幫助。
查看完整描述

1 回答

?
牧羊人nacy

TA貢獻1862條經(jīng)驗 獲得超7個贊

大多數(shù)教程使用localStorageorcookie是因為您希望即使在用戶刷新頁面后也保留登錄狀態(tài),這樣他們就不必每次都重新登錄。但要回答你的問題,你可以這樣做:


import React, { useState } from "react";

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

import "./style.css";

import axios from "axios";


function yourLoginPostApi() {

  return new Promise(r => setTimeout(() => r(true), 1000));

}


function Login({ onSuccess }) {

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

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

  let [loading, setLoading] = useState(false);

  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();

    setLoading(true);

    // Uncomment this line and remove the next one since it's a fake api call

    // let response = await axios.post("http://localhost:5000/users/login", user);

    let response = await yourLoginPostApi();

    setLoading(false);

    onSuccess(response);

  };

  return (

    <div className="Login">

      <h2>Traffic scan admin panel</h2>

      <div className="LoginInfo-Logins">

        <form>

          <input

            type="text"

            required

            className=""

            value={username}

            onChange={onChangeUsername}

            placeholder="Username*"

          />

          <input

            type="text"

            required

            className=""

            value={password}

            onChange={onChangePassword}

            placeholder="Password*"

          />

        </form>

      </div>

      <button onClick={onSubmit}>SIGN IN</button>

      <div>{loading && "Please wait..."}</div>

    </div>

  );

}


function PrivateRoute({ children }) {

  let [loggedIn, setLoggedIn] = useState(false);

  return loggedIn ? (

    <div>

      {children}

      <button onClick={() => setLoggedIn(false)}>log out</button>

    </div>

  ) : (

    <Login onSuccess={() => setLoggedIn(true)} />

  );

}


export default function App() {

  return (

    <BrowserRouter>

      <PrivateRoute>

        <div>Stuff only a logged in user should see</div>

      </PrivateRoute>

    </BrowserRouter>

  );

}


你可以在 stackblitz 上看到演示


查看完整回答
反對 回復 2023-10-14
  • 1 回答
  • 0 關(guān)注
  • 108 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號