代码之家  ›  专栏  ›  技术社区  ›  Agrim Singh

用户数据。名称未显示用户名

  •  1
  • Agrim Singh  · 技术社区  · 2 年前

    我正在学习 梅恩 我创建了一个简单的网站,你可以登录和注册。

    登录和注册功能工作正常,但我的关于页面有一些错误。

    如果您没有登录(基于Cookie部分中的令牌),并且您单击about(关于)将重定向到登录页面,并且如果您登录,它将显示您的详细信息,那么about(关于)页面的问题很简单。

    当我从MongoDB获取所有数据时,我将其存储在一个变量中 data . 我已经存储了 数据 在一个 useState(); 已命名 userData .

    当我 console.log(userData); 它向我展示了所有好的细节 console.log(userData.name) ,它也显示了用户的名称。

    但当我给同样的 userData.name 在里面 h5 ,它显示了一个错误。

    我给出了这样的信息: <h5>{userData.name}</h5> .

    我的全部关于。js代码:

    import React from 'react';
    import agrim from "../images/agrim.jpeg";
    import { useNavigate } from "react-router-dom";
    
    const About = () => {
    
      const navigate = useNavigate();
    
      const [userData, setUserData] = React.useState();
    
      const callAboutPage = async () => {
        try {
          const res = await fetch("/about", {
            method: "GET",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json"
            },
            credentials: "include"
          });
    
          const data = await res.json();
    
          setUserData(data);
    
          if(!res.status === 200) {
            const error = new Error(`An Error Occurred: ${res.error}`);
            console.log(error);
            throw error;
          }
        } catch (error) {
          console.log(`An Error Occurred: ${error.message}`);
          navigate("/login");
        }
      }
    
      React.useEffect(() => {
        callAboutPage();
      }, [callAboutPage]);
    
      return (
        <>
          <div className="container emp-profile mt-4">
            <form method="GET">
              <div className="row">
                <div className="col-md-4">
                  <div className="profile-img">
                    <img src={agrim} alt="Agrim Singh" />
                  </div>
                </div>
    
                <div className="col-md-6 profile-head">
                  <h5 onClick={() => console.log(userData.name)}>{userData.name}</h5>
                  <h6>Web Developer, Student</h6>
                  <p>
                    RANKINGS : <span>1/10</span>
                  </p>
    
                  <ul className="nav nav-tabs" role="tablist">
                    <li className="nav-item">
                      <a
                        href="#home"
                        className="nav-link-active mr-4"
                        id="home-tab"
                        data-toggle="tab"
                        role="tab"
                      >
                        About
                      </a>
                    </li>
    
                    <li className="nav-item">
                      <a
                        href="#profile"
                        className="nav-link-active"
                        id="profile-tab"
                        data-toggle="tab"
                        role="tab"
                      >
                        Timeline
                      </a>
                    </li>
                  </ul>
                </div>
                <div className="col-md-2">
                  <input type="submit" className="profile-edit-btn" name="btnAddMore" value="Edit Profile" />
                </div>
              </div>
    
              <div className="row">
                <div className="col-md-4">
                  <div className="profile-work">
                    <p>WORK LINK</p>
                    <a href="https://www.youtube.com/channel/UCdfS-7bgMHA_x-0u7pxjZng" target="_youtube">Youtube</a> <br />
                    <a href="https://instagram.com/ff_player.agrim" target="_instagram">Instagram</a> <br />
                    <a href="https://gsonline.vercel.app/" target="_gsonline">GSOnine</a> <br />
                    <a href="https://agrimpay-paymentapp.web.app/" target="_agrimpay">Agrim Pay</a> <br />
                    <a href="https://mernagrimatechnical.herokuapp.com/" target="_agrimpay">Agrim Technical</a> <br />
                    <a href="https://www.github.com/AgrimSingh421" target="_github">Github</a>
                  </div>
                </div>
    
                <div className="col-md-8 pl-5 about-info">
                  <div className="tab-content profile-tab" id="myTabContent">
                    <div className="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
                      <div className="row">
                        <div className="col-md-6">
                          <label>User ID</label>
                        </div>
                        <div className="col-md-6">
                          <p>45899963254778996541</p>
                        </div>
                      </div>
    
                      <div className="row mt-3">
                        <div className="col-md-6">
                          <label>Name</label>
                        </div>
                        <div className="col-md-6">
                          <p>{userData.name}</p>
                        </div>
                      </div>
    
                      <div className="row mt-3">
                        <div className="col-md-6">
                          <label>Email</label>
                        </div>
                        <div className="col-md-6">
                          <p>singhagrim36@gmail.com</p>
                        </div>
                      </div>
    
                      <div className="row mt-3">
                        <div className="col-md-6">
                          <label>Phone</label>
                        </div>
                        <div className="col-md-6">
                          <p>8996325410</p>
                        </div>
                      </div>
    
                      <div className="row mt-3">
                        <div className="col-md-6">
                          <label>Profession</label>
                        </div>
                        <div className="col-md-6">
                          <p>Web Developer, Student</p>
                        </div>
                      </div>
                    </div>
    
                    <div className="tab-pane fade show active" id="profile" role="tabpanel" aria-labelledby="profile-tab">
                      <div className="row">
                        <div className="col-md-6">
                          <label>Experience</label>
                        </div>
                        <div className="col-md-6">
                          <p>Intermediate</p>
                        </div>
                      </div>
    
                      <div className="row mt-3">
                        <div className="col-md-6">
                          <label>Hourly Rate</label>
                        </div>
                        <div className="col-md-6">
                          <p>₹599/hr</p>
                        </div>
                      </div>
    
                      <div className="row mt-3">
                        <div className="col-md-6">
                          <label>Total Projects</label>
                        </div>
                        <div className="col-md-6">
                          <p>24</p>
                        </div>
                      </div>
    
                      <div className="row mt-3">
                        <div className="col-md-6">
                          <label>Availibility</label>
                        </div>
                        <div className="col-md-6">
                          <p>10 Months</p>
                        </div>
                      </div>
    
                      <div className="row mt-3">
                        <div className="col-md-6">
                          <label>English Level</label>
                        </div>
                        <div className="col-md-6">
                          <p>Intermediate</p>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </form>
          </div>
        </>
      );
    };
    
    export default About;
    

    我没有在其他领域给出答案,因为如果 用户数据。名称 会没事的,别人也会好去的。

    我的完全身份验证。js代码:

    //_ Requiring Modules
    const jwt = require("jsonwebtoken");
    const User = require("../model/userSchema");
    
    //_ Making authenticate function to use in auth.js
    const authenticate = async (req,  res, next) => {
        try {
            const token = req.cookies.jwtoken;    //_ Getting Token from cookies
            const verifyToken = jwt.verify(token, process.env.SECRET_KEY);    //_ Verifiying token and storing it into a variable
    
            const rootUser = await User.findOne({ _id: verifyToken._id, "tokens.token": token });    //_ If the token in the cookies section from the browser is matched from the token from the database, it means the user is available and we can show him his about page
    
            if(!rootUser) { throw new Error("User not found!") }
    
            //_ Getting all data
            req.token = token;
            req.rootUser = rootUser;
            req.userID = rootUser._id;
    
            next();    //_ Calling next() to do other things. Im simple words: AAGE BADHO AAGE!
        } catch (error) {
            res.status(401).send("Unauthorized: No token provided");
            console.log(`An Error Occurred: ${error.message}`);
        }
    }
    
    //_ Exporting authenticate function
    module.exports = authenticate;
    

    我有授权书。我在其中调用的js文件关于页面

    router.get("/about", authenticate, (req, res) => {
        res.send(req.rootUser);
    });
    

    我导入了如下路由器:

    const express = require("express");
    const router = express.Router();
    

    我导出的路由器如下: module.exports = router;

    任何帮助都将不胜感激。。。

    1 回复  |  直到 2 年前
        1
  •  1
  •   Suryansh Kushwaha    2 年前

    您必须更改useState类型:

    const [userData, setUserData] = useState({}):