Мой API дает правильный ответ с помощью почтальона.
Я проверил буквально все, что я получаю, это пустой массив сеансов, кстати, моя аутентификация работает нормально. Я проверил маршрут, порт, они все правильные.
Фронтенд → GET http://localhost:8080/api/sessions
Бэкенд → ответы 404 не найден, я не почему
http://localhost:8080/api/sessions это маршрут
и это ответ
{
"sessions": [
{
"_id": "690641e12846bc196718843c",
"user": "69035b1a0ac66655760f6aa9",
"role": "Python dev",
"experience": "10 years",
"topicsToFocus": "Node.js, MongoDB, Express",
"description": "Preparing for backend system design and API performance questions.",
"questions": [
{
"_id": "690641e12846bc196718843d",
"session": "690641e12846bc196718843c",
"question": "What is middleware in Express?",
"answer": "Middleware functions are functions that have access to the request and response objects and can modify or end the request-response cycle.",
"isPinned": false,
"__v": 0,
"createdAt": "2025-11-01T17:22:41.044Z",
"updatedAt": "2025-11-01T17:22:41.044Z"
},
{
"_id": "690641e12846bc196718843e",
"session": "690641e12846bc196718843c",
"question": "How does MongoDB handle indexing?",
"answer": "MongoDB uses B-tree indexes to improve query performance by reducing the amount of data it needs to scan.",
"isPinned": false,
"__v": 0,
"createdAt": "2025-11-01T17:22:41.044Z",
"updatedAt": "2025-11-01T17:22:41.044Z"
},
{
"_id": "690641e12846bc196718843f",
"session": "690641e12846bc196718843c",
"question": "Explain event-driven architecture in Node.js.",
"answer": "Node.js operates on a single-threaded event loop using non-blocking I/O for handling multiple requests efficiently.",
"isPinned": false,
"__v": 0,
"createdAt": "2025-11-01T17:22:41.044Z",
"updatedAt": "2025-11-01T17:22:41.044Z"
}
],
"createdAt": "2025-11-01T17:22:41.083Z",
"updatedAt": "2025-11-01T17:22:41.083Z",
"__v": 0
},
{
"_id": "690641ab2846bc1967188432",
"user": "69035b1a0ac66655760f6aa9",
"role": "Backend Developer",
"experience": "3 years",
"topicsToFocus": "Node.js, MongoDB, Express",
"description": "Preparing for backend system design and API performance questions.",
"questions": [
{
"_id": "690641ab2846bc1967188433",
"session": "690641ab2846bc1967188432",
"question": "What is middleware in Express?",
"answer": "Middleware functions are functions that have access to the request and response objects and can modify or end the request-response cycle.",
"isPinned": false,
"__v": 0,
"createdAt": "2025-11-01T17:21:47.730Z",
"updatedAt": "2025-11-01T17:21:47.730Z"
},
{
"_id": "690641ab2846bc1967188434",
"session": "690641ab2846bc1967188432",
"question": "How does MongoDB handle indexing?",
"answer": "MongoDB uses B-tree indexes to improve query performance by reducing the amount of data it needs to scan.",
"isPinned": false,
"__v": 0,
"createdAt": "2025-11-01T17:21:47.731Z",
"updatedAt": "2025-11-01T17:21:47.731Z"
},
{
"_id": "690641ab2846bc1967188435",
"session": "690641ab2846bc1967188432",
"question": "Explain event-driven architecture in Node.js.",
"answer": "Node.js operates on a single-threaded event loop using non-blocking I/O for handling multiple requests efficiently.",
"isPinned": false,
"__v": 0,
"createdAt": "2025-11-01T17:21:47.731Z",
"updatedAt": "2025-11-01T17:21:47.731Z"
}
],
"createdAt": "2025-11-01T17:21:47.780Z",
"updatedAt": "2025-11-01T17:21:47.780Z",
"__v": 0
},
{
"_id": "6906158feba43303b03cef50",
"user": "69035b1a0ac66655760f6aa9",
"role": "Backend Developer",
"experience": "2 years",
"topicsToFocus": "Node.js, Express, MongoDB",
"description": "Practice API design and database relations",
"questions": [
{
"_id": "6906158feba43303b03cef51",
"session": "6906158feba43303b03cef50",
"question": "What is middleware in Express?",
"answer": "Middleware functions are functions that have access to req, res, and next objects in Express.",
"isPinned": false,
"__v": 0,
"createdAt": "2025-11-01T14:13:35.208Z",
"updatedAt": "2025-11-01T14:13:35.208Z"
},
{
"_id": "6906158feba43303b03cef52",
"session": "6906158feba43303b03cef50",
"question": "How do you connect MongoDB to Node.js?",
"answer": "Using Mongoose connect() with the MongoDB URI in your app.js file.",
"isPinned": false,
"__v": 0,
"createdAt": "2025-11-01T14:13:35.210Z",
"updatedAt": "2025-11-01T14:13:35.210Z"
}
],
"createdAt": "2025-11-01T14:13:35.257Z",
"updatedAt": "2025-11-01T14:13:35.257Z",
"__v": 0
}
]
}
import React, { useEffect, useState } from "react";
import { LuPlus } from "react-icons/lu";
import { useNavigate } from "react-router-dom";
import toast from "react-hot-toast";
import { CARD_BG } from "../../utils/data.js";
import DashboardLayout from "../../components/layouts/DashboardLayout.jsx";
import SummaryCard from "../../components/Cards/SummaryCard.jsx";
import { axiosInstance } from "../../utils/axiosInstance.js";
const Dashboard = () => {
const navigate = useNavigate();
const [sessions, setSessions] = useState([]);
const [loading, setLoading] = useState(false);
const [openCreateModel, setOpenCreateModel] = useState(false);
const [openDeleteAlert, setOpenDeleteAlert] = useState({
open: false,
data: null,
});
const getMySessions = async () => {
setLoading(true);
try {
const res = await axiosInstance.get("/sessions");
console.log("API Response:", res.data);
// adjust depending on backend shape
setSessions(res.data.sessions);
} catch (error) {
console.error(" Error fetching sessions:", error);
toast.error("Failed to load sessions");
} finally {
setLoading(false);
}
};
useEffect(() => {
getMySessions();
}, []);
useEffect(() => {
console.log("Updated sessions:", sessions);
}, [sessions]);
Если кому-то интересно узнать мой серверный API
app.use("/api/sessions", sessionRoutes);
это sessionRoute
router.get("/", protect, getMySession);
это контроллер
export const getMySession = async (req, res) => {
try {
const sessions = await Session.find({ user: req.user._id }) //
.sort({ createdAt: -1 })
.populate("questions");
if (!sessions || sessions.length === 0) {
return res.status(404).json({ message: "No sessions found" });
}
return res.status(200).json({ sessions });
} catch (error) {
console.error("Error fetching sessions:", error);
return res
.status(500)
.json({ message: "Error fetching sessions", error: error.message });
}
};
это промежуточное ПО для аутентификации
import jwt from "jsonwebtoken";
import User from "../model/User.js";
export const protect = async (req, res, next) => {
// 1. Read the token from the cookie
const token = req.cookies.jwt;
if (!token) {
// Unauthorized (401) if no token is present
return res.status(401).json({ message: "Not authorized, no token provided." });
}
try {
// 2. Verify the token (jwt.verify throws on failure: expired, invalid signature, etc.)
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// 3. Find the user attached to the token
const user = await User.findById(decoded.userId).select("-password");
if (!user) {
// Unauthorized (401) if token is valid but user no longer exists
return res.status(401).json({ message: "Not authorized, user no longer exists." });
}
// 4. Attach user object to the request
req.user = user;
// 5. Continue to the next middleware/controller
next();
} catch (error) {
// Handles errors thrown by jwt.verify (e.g., token expired, invalid signature)
// Log the actual error on the backend for debugging
console.error("JWT verification failed:", error.message);
return res.status(401).json({ message: "Not authorized, token failed verification." });
}
};
Подробнее здесь: https://stackoverflow.com/questions/798 ... -and-route
Мобильная версия