如何使用节点 js 、 react js 、 sql 中的会话以表格格式显示登录的用户详细信息?

Posted

技术标签:

【中文标题】如何使用节点 js 、 react js 、 sql 中的会话以表格格式显示登录的用户详细信息?【英文标题】:How to display the logged in user details in a table format using session in node js , react js , sql? 【发布时间】:2021-09-10 14:59:44 【问题描述】:

This the view page where user details are redirected

大家好,目前我正在处理一个有两个表单登录和用户详细信息表单的项目。 当用户登录并填写详细信息表单后,它将重定向到查看页面,他/她可以查看,编辑,删除他/她的记录。但是当用户登录时,只能看到他的记录。就我而言,它正在获取视图页面中的所有记录。我在节点 js 中使用会话。我不知道出了什么问题。

服务器代码

const express = require("express");
const app = express();
const cors = require('cors');
const mysql = require("mysql");
const cookie=require("cookie-parser");
const session=require("express-session");
const bodyparser=require("body-parser");
app.use(cors(
    origin:("http://localhost:3000"),
    methods:("GET","POST"),
    credentials:true
));
app.use(cookie("secret"));
app.use(bodyparser.urlencoded(extended:true));
app.use(session(
    key:"userid",
    resave:false,
    saveUninitialized:false,
    secret:"userinfo",
    cookie:
        expires:60*60*24,
    ,
))

app.use(express.json());
const db = mysql.createConnection(
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'demo'
);
db.connect((err) => 
    if (err) 
        throw err;
    
    else 
        console.log("Mysql Connected");
    
)

//var sess
app.post('/register', (req, res) => 
    const email = req.body.email;
    const password = req.body.password;
    const cpassword = req.body.cpassword;
    db.query("SELECT  FROM registration WHERE email='"+email+"';", [email], (err, result) => 
        if(result)
            res.send(message:"User already exists")
        
        else
            db.query("INSERT INTO registration (email,password,cpassword) VALUES(?,?,?)", [email, password, cpassword], (err, result) => 
               if(err)
                   res.send(err);
               
               else
                   res.send(message:"Registered Successful")
               
            )
        
    )

    
)

app.post("/login", (req, res) => 
    const email = req.body.email;
    const password = req.body.password;
    db.query("SELECT * FROM registration WHERE  email='"+email+"' AND password='"+password+"';", [email,password], (err, result) => 
        if(err)
            res.send(err:err);

        
        if(result.length>0)
              req.session.user=result;
              console.log( req.session.user)
              res.send(result);
            // sess=req.session;
            // sess.userid=req.body.email;
            //  console.log(req.session)
             
        else
            res.send(message:"Wrong username/passsword")
        
    )
     app.get("/login",(req,res)=>
         if(req.session.user)
             res.send(loggedIn:true,user:req.session.user)
            
         
         else
             res.send(loggedIn:false);
     
     
 )
 app.post('/add', (req, res) => 
        const firstname=req.body.firstname;
        const lastname=req.body.lastname;
        const email=req.body.email;
        const mobile=req.body.mobile;
        const address=req.body.address;
        const city=req.body.city;
        const pincode=req.body.pincode;
        const conference=req.body.conference;
        const seminar=req.body.seminar;
        const paper=req.body.paper;
        //const user_id=req.body.user_id;
       
        if(firstname==""||lastname==""||email==""||mobile==""||address==""||city==""||pincode==""||conference==""||seminar==""||paper=="")
        
            return res.status(422).json(error:"Please Fill the form correctly");
    
        
        
           
        db.query("INSERT INTO teacher  (firstname,lastname,email,mobile,address,city,pincode,conference,seminar,paper) VALUES(?,?,?,?,?,?,?,?,?,?)", [firstname,lastname,email,mobile,address,city,pincode,conference,seminar,paper], (err, result) => 
             console.log(err)   
            
        //    if(result)
        //     //sess=req.session;
        //     req.session.user=result;
        //     console.log(req.session.user)
        //     res.send(result)
            //sess.email=req.body.email;
            //if(sess.email)
            //console.log( sess)
            //res.send(result)
            //res.redirect("/view");
           
            //
           
          //    
        //   else
        //       res.send(err)
        //  
           
        )
            
        
    )
    

        
            
//  )
//   
 app.get("/teachersdata" , (req, res) => 
     
     db.query("SELECT * FROM teacher ",(err,result)=>
          if(result)
        
          res.send(result);
        
           
            
    
        
        
     
    
        
 )
 app.get("/teachersdata/:id", (req, res) => 

      db.query('SELECT * FROM teacher WHERE id=?',[req.params.id], (err, result)=>
          if(err)
              console.log('Error while fetching employee by id', err);
             
          else
              res.send(result)
          
      )
    
        
 )
    app.get("/logout",(req,res)=>
        console.log("logout page");
        //req.logout()
        console.log( req.session.user)
        res.clearCookie("user")
        //res.redirect("/login")
        req.session.destroy((err) => 
            res.redirect('/login') // will always fire after session is destroyed
          )

    )

)
app.put('/edit/:id',(req,res)=>
    const firstname=req.body.firstname;
    const lastname=req.body.lastname;
    const email=req.body.email;
    const mobile=req.body.mobile;
    const address=req.body.address;
    const city=req.body.city;
    const pincode=req.body.pincode;
    const conference=req.body.conference;
    const seminar=req.body.seminar;
    const paper=req.body.paper;
    const id=req.params.id;
    db.query("UPDATE teacher SET firstname=?,lastname=?,mobile=?,email=?,address=?,city=?,pincode=?,conference=?,seminar=?,paper=? WHERE id=?",[id,firstname,lastname,email,mobile,address,city,pincode,conference,seminar,paper],(err,res)=>
        if(err)
            console.log(err)
        
        else
            res.send(res);
        
    )
)
app.delete("/delete/:id",(req,res)=>
    db.query("DELETE FROM teacher WHERE id=?",[req.params.id],(result,err)=>
        if(err)
            res.send(err)
        
        else
            res.send(result)
        
    )
)
app.listen(3001)

这是反应代码

import React from 'react';
import axios from 'axios';
import  useState,useEffect  from 'react';
import  Link  from 'react-router-dom';

export const View = () => 
   const [teacherList, setteacherList] = useState([]);
   
  useEffect(() => 
    loadUsers();
  , [])
  const loadUsers= async()=>
    const result =await axios.get("http://localhost:3001/teachersdata");
    console.log(result)
    setteacherList(result.data)
  
 
  


const deleteUser = async id => 
  await axios.delete(`/delete/$id`);
  loadUsers();
;

 
  return (
    <div>
       
      <table class="table">
  <thead class="thead-dark">
    <tr>
      <th scope="col">#</th>
      <th scope="col">FirstName</th>
      <th scope="col">LastName</th>
      <th scope="col">Email</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    
      teacherList.map((user,index)=>(
        <tr>
          <th scope="row">index+1</th>
          <td>user.firstname</td>
          <td>user.lastname</td>
          <td>user.email</td>
          <td>
           
            <Link class="btn btn-primary me-md-2" to=`/teachersdata/$user.id`>View</Link>
            <Link class="btn btn-outline-primary me-md-2" to=`/edit/$user.id`>Edit</Link>
            <Link class="btn btn-danger" onClick=() => deleteUser(user.id)>Delete</Link>
            
          </td>
          </tr>
         
      ))
    
  </tbody>
</table>
    </div>

  )


登录页面(客户端)

import React from 'react'
import  useState  from 'react';
import axios from 'axios';
import useHistory from 'react-router-dom';

const Login = () => 
    axios.defaults.withCredentials=true;
    const history=useHistory();
    const [emailreg,setemail]=useState('');
    const [pas-s-reg,setpass]=useState('');
    
    const login=()=>
        
        axios.post("/login",
            email:emailreg,
            password:pas-s-reg,

        ).then((res)=>
            //alert(res.data.message)
            //setLoginUser(res.data.user)
            //history.push("/add")
              //console.log(res);
             if(res.data.message)
                  alert(res.data.message);
              
              else
                 alert("Login Sucessfully");
                  history.push("/add")
          
            
        )
        
        
    
    

    return (
    
            <div className="login">
            <h1>Login</h1>
            <label>Email ID</label>
            <input type="text" onChange=(e)=>
                setemail(e.target.value);
            /><br/>
            <label>Password</label>
            <input type="password" onChange=(e)=>
                setpass(e.target.value);
            /><br/>
            <button onClick=login>Login</button>
            
            
        </div>
        
        
    )


export default Login

用户详情页面

import  useState  from 'react'
import axios from 'axios';
import useHistory from 'react-router-dom';
import  useEffect  from 'react';
const Main = () => 
  const [formStep, setFormStep] = useState(0);
  const history=useHistory();

   
    const [firstname,setfirstname]=useState('');
    const [lastname,setlastname]=useState('');
    const [email,setemail]=useState('');
    const [mobile,setmobile]=useState('');
    const [address,setaddress]=useState('');
    const [city,setcity]=useState('');
    const [pincode,setpincode]=useState('');
    const [conference,setconference]=useState('');
    const [seminar,setseminar]=useState('');
    const [paper,setpaper]=useState('');
    const [loginstatus,setlogin]=useState('');
    //const [userid,setuserid]=useState('');

  const completeFormStep = () => 
    setFormStep(step => step + 1)
  
  const backFormStep = () => 
    setFormStep(step => step - 1)
  
  
  const handlesubmit = () => 
    axios.post("http://localhost:3001/add",
            firstname:firstname,
            lastname:lastname,
            email:email,
            mobile:mobile,
            address:address,
            city:city,
            pincode:pincode,
            conference:conference,
            seminar:seminar,
            paper:paper,
            //userid:userid

           

        ).then((res)=>
            console.log("success");
           
           
            
           
           
            
        )
        

        history.push("/view")

        
  ;
  
    useEffect(() => 
      axios.get("/login").then((res)=>
          console.log(res)
          if(res.data.loggedIn===true)
          setlogin(res.data.user[0].email)
          // if(res.data.loggedIn===true)
          // setlogin(res.data.userid)
         
      )
  , []);

  
  return (
    <div className="create">
      <form method="POST">
        formStep === 0 && (
          <section>
             <h1>"Welcome" + loginstatus</h1> 
            <h2>Names</h2>

            <label>First Name</label>
            <input
              type="text"
              required
              onChange=(e)=>
                setfirstname(e.target.value);
            
              

            />


            <br />

            <label>Last Name</label>
            <input
              type="text"
              required
              onChange=(e)=>
                setlastname(e.target.value);
            

            />

            <br />
            <button type="button" onClick=completeFormStep>Next</button>
          </section>)

        <div className="step2">
          formStep === 1 && (
            <section>
              <h2>Contact</h2>

              <label>Email ID</label>
              <input
                type="email"
                required
                onChange=(e)=>
                  setemail(e.target.value);
              

              />
              <br />
              /* <label>UserID</label>
              <input
                type="userid"
                required
                onChange=(e)=>
                  setuserid(e.target.value);
              
              />
              <br/>  */
              <label>Mobile No.</label>
              <input
                type="text"
                required
                onChange=(e)=>
                  setmobile(e.target.value);
              

              />
              <br />
              <button type="button" onClick=backFormStep>Back</button>
              <button type="button" onClick=completeFormStep>Next</button>
            </section>)
        </div>

        <div className="step3">
          formStep === 2 && (
            <section>
              <h2>Address</h2>
              <label>Address</label>
              <textarea onChange=(e)=>
                setaddress(e.target.value);
            >

              </textarea>
              <br />

              <label>City</label>
              <input
                type="text"
                required
                onChange=(e)=>
                  setcity(e.target.value);
              
              />
              <br />
              <label>Pincode</label>
              <input
                type="text"
                required
                onChange=(e)=>
                  setpincode(e.target.value);
              

              />
              <br />
              <button type="button" onClick=backFormStep>Back</button>
              <button type="button" onClick=completeFormStep>Next</button>

            </section>)
        </div>
        <div className="step4">
          formStep === 3 && (
            <section>
              <h2>Conferences attended,seminar and paper presented</h2>

              <label>Conferences name</label>
              <textarea placeholder="conferences names" onChange=(e)=>
                setconference(e.target.value);
            ></textarea>

              <br />
              <label>Seminar attended</label>
              <textarea placeholder="seminar names"onChange=(e)=>
                setseminar(e.target.value);
            ></textarea>

              <br />
              <label>Paper presented</label>
              <textarea placeholder="paper names" onChange=(e)=>
                setpaper(e.target.value);
            ></textarea>
              <br />
              <button type="button" onClick=backFormStep>Back</button>
              <button type="submit" onClick=handlesubmit>Submit</button>
             
            </section>)
          <div>


          
          </div>
         

        </div>




      </form>










    </div>
  );


export default Main

我希望当用户登录并填写详细信息表单时,应该只显示他或登录的用户详细信息,每个用户应该在登录后在查看页面中获得自己的详细信息。我是 node js 的新手并做出反应。

提前致谢

【问题讨论】:

您在客户端登录的逻辑在哪里? @SanishJoseph 我现在编辑了我的帖子检查 登录后,您将转到add 路由,我假设它指向Main 组件,并且没有逻辑可以查看用户是否已登录该组件。在您的登录屏幕中,您没有对收到的响应做任何事情。我将添加休息作为答案。 【参考方案1】:

我可以看到您在登录后发送loggedIn:true,user:req.session.user,但您的客户端应用程序现在忽略了它。您可以做的是保存您在本地存储登录后收到的这个对象,这样即使他们刷新页面,我们也可以访问该对象。

将对象保存到本地存储后,在您的Main 组件中,您需要检查本地存储中是否存在对象并且loggedIn 的值为true 并且user 会话对象尚未过期。如果其中任何一个条件不满足,则必须清除本地存储并将用户重定向到登录页面。

我不确定user 对象中的会话是否过期,但您肯定有一个过期的cookie。

我希望它很清楚。

【讨论】:

是的,我会试试的,非常感谢

以上是关于如何使用节点 js 、 react js 、 sql 中的会话以表格格式显示登录的用户详细信息?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 React js 绘制简单的迷你图?

如何使用节点 js 从后端 API 请求 apikey?

如何在反应节点 js 项目中从客户端创建动态元标记?

如何在同一个存储库中使用 React.js 和 Node.js

react获取DOM节点

如何将值从反应本机应用程序传递到节点 js 后端