无法在 React 应用程序中从 MongoDB 检索学生数据 - 500 内部服务器错误

问题描述 投票:0回答:1

问题:

我正在开发一个 React 应用程序,其后端是使用 Express 和 MongoDB 构建的。我在尝试获取学生个人资料数据时遇到问题。浏览器控制台显示 500 内部服务器错误。

后端设置:

  • 后端:Express、MongoDB

  • 相关代码片段

    • studentModel.js:
    • const mongoose = require("mongoose");
      
      const studentSchema = new mongoose.Schema({
        userId: mongoose.Schema.Types.ObjectId, // Reference to the User model
        personalDetails: {
          name: String,
          email: String,
          registerNumber: String,
          department: String,
          college: String,
          program: String,
          specialization: String,
          education: String,
          section: String,
        },
        professionalDetails: {
          skills: String,
          areaOfInterest: String,
          languages: [String],
        },
        documents: {
          photo: String, // Storing file paths or URLs
          resume: String,
          cv: String,
        },
      });
      
      const Student = mongoose.model("Student", studentSchema);
      module.exports = Student;
      
      

studentController.js:

exports.getStudent = async (req, res) => {
  try {
    const student = await Student.findById(req.params.id);
    if (!student) {
      return res.status(404).send();
    }
    res.send(student);
  } catch (error) {
    res.status(500).send();
  }
};

前端设置:

  • 前端:React

  • 相关代码片段

    • ProfilePage.js
import React, { useEffect, useState } from "react";
import StudentHeader from "../Header/StudentHeader";
import Footer from "../Footer/Footer";
import "../../styles/ApplyForInterview.css";

const ProfilePage = () => {
  const [studentData, setStudentData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchStudentData = async () => {
      try {
        const token = localStorage.getItem("token");
        if (!token) {
          throw new Error("Authentication required");
        }

        const response = await fetch("/api/v1/students/profile", {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
        });

        if (!response.ok) {
          throw new Error(`Error ${response.status}: ${response.statusText}`);
        }

        const data = await response.json();
        setStudentData(data);
      } catch (error) {
        setError(error.message);
      }
    };

    fetchStudentData();
  }, []);

  if (error) {
    return <div>Error: {error}</div>;
  }

  if (!studentData) {
    return <div>Loading...</div>;
  }

  const { personalDetails, professionalDetails, documents } = studentData;

  return (
    <div className="growwithguru-container">
      <StudentHeader />
      <div className="form-container">
        <h1>Welcome to GROW WITH GURU - Your Path to Interview Success</h1>
        <div className="form-box profile-section">
          <div className="profile-photo-placeholder">
            {documents?.photo ? (
              <img src={documents.photo} alt="Student" />
            ) : (
              <div>No Photo Available</div>
            )}
          </div>
          <div className="profile-info-section">
            {/* Personal Details */}
            <div className="profile-info-group">
              <label className="profile-label">Name:</label>
              <div className="profile-value">
                {personalDetails?.name || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Email ID:</label>
              <div className="profile-value">
                {personalDetails?.email || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Register No:</label>
              <div className="profile-value">
                {personalDetails?.registerNumber || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Department:</label>
              <div className="profile-value">
                {personalDetails?.department || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">College:</label>
              <div className="profile-value">
                {personalDetails?.college || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Program:</label>
              <div className="profile-value">
                {personalDetails?.program || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Specialization:</label>
              <div className="profile-value">
                {personalDetails?.specialization || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Education:</label>
              <div className="profile-value">
                {personalDetails?.education || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Section:</label>
              <div className="profile-value">
                {personalDetails?.section || "N/A"}
              </div>
            </div>
            {/* Professional Details */}
            <div className="profile-info-group">
              <label className="profile-label">Skills:</label>
              <div className="profile-value">
                {professionalDetails?.skills || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Area of Interest:</label>
              <div className="profile-value">
                {professionalDetails?.areaOfInterest || "N/A"}
              </div>
            </div>
            <div className="profile-info-group">
              <label className="profile-label">Languages:</label>
              <div className="profile-value">
                {professionalDetails?.languages?.join(", ") || "N/A"}
              </div>
            </div>
          </div>
        </div>
      </div>
      <Footer />
    </div>
  );
};

export default ProfilePage;

错误详情:

当我尝试访问个人资料页面时发生错误。控制台日志显示:

GET http://localhost:3000/api/v1/students/profile 500(内部服务器错误)

这是我的项目的 github 链接,对我有帮助:https://github.com/vamshigadde09/GROW-WITH-GURU

我尝试过的:

  • 已验证 MongoDB 正在运行且可访问。

  • 检查路线和控制器以确保它们定义正确。

  • 确认令牌存在并且在请求中正确使用。

附加信息:

  • 后端服务器日志:没有具体的错误消息,只有 500 状态代码。

  • 前端框架:React

  • 后端框架:Express

reactjs mongodb express http-status-code-500
1个回答
0
投票

将日志添加到 catch 部分。这会将所有错误记录到控制台,这可以帮助诊断问题。

} catch (error) {
  console.error("Error fetching student:", error); // Log the error
  res.status(500).send();
}
© www.soinside.com 2019 - 2024. All rights reserved.