How can I use passportjs and reactjs together?

后端 未结 4 1564
旧巷少年郎
旧巷少年郎 2021-02-05 08:06

I have 3 views, (Home, signup, login)made in reactJs, I want to use passport in my project but I dont know how to do it, I have passport configurated and it url is working.

4条回答
  •  误落风尘
    2021-02-05 08:50

    • Use componentDidMount/useEffect to get authentication status. Set status in react state.
    • If not authenticated, Show the link to Login/Signup page or redirect.
    • If authenticated, you can return additional protected data or show the link to the protected page.(When showing private data, check authentication status on every page by using componentDidMount/useEffect)

    Client-side example

    import React, { useEffect, useState } from 'react';
    import { Link } from "react-router-dom";
    import axios from 'axios';
    
    function Home() {
    
      const [loggedIn, setLoggedIn] = useState(false);
    
      useEffect(() => {
        axios.get('/checkAuthentication')
          .then(res => {
            setLoggedIn(res.data.authenticated);
          })
          .catch((error) => {
            setLoggedIn(false)
        });
      }, []);
    
      return (
        
    {loggedIn ? (

    Login success

    ) : (
    Signup Login
    )}
    ); } export default Home;

    Server-side example (req.user must be populated if you set up passport)

    app.get("/checkAuthentication", (req, res) => {
      const authenticated: boolean = typeof req.user !== 'undefined'
    
      res.status(200).json({
        authenticated,
      });
    });
    

提交回复
热议问题