0

I am attempting to retrieve data from a Node.js + MongoDB backend to a React.js frontend. To ensure secure access, I'm utilizing a JWT token for authentication. There are two distinct APIs available for data retrieval: one that doesn't require a JWT token and another that does. Strangely, I can successfully obtain data when not using the JWT token, but encounter an error when attempting to use it. The backend appears to be functioning correctly, as it's already in use for a mobile app and has undergone development. I would greatly appreciate any assistance or guidance on this matter.

API Error: TypeError: NetworkError when attempting to fetch resource.

This is data fetch react js code.

    import { useEffect, useState } from "react";


function ForumComponent() {
  const [forums, setForums] = useState([]);

  useEffect(() => {
    const fetchForums = async () => {
      const accessToken = localStorage.getItem("user");

      if (!accessToken) {
        console.log("No token found.");
        return;
      }

      try {
        console.log(accessToken);
        
        const response = await fetch("/api/forums", {
          headers: {
            Authorization: `Bearer ${accessToken}`,
          },
        });
        const json = await response.json(); // Await the parsing of the JSON
        console.log(json); // Debugging
        setForums(json);
      } catch (error) {
        console.log("API Error:", error); // Debugging
      }
    };

    fetchForums();
      }, []);
    
      return forums;
    }
    
    export default ForumComponent;

and this is UI code

import React, { useState, useEffect } from "react";
import { Layout } from "../components";
import Post from "../components/Post";
import useFetchForums from "../api/forumFetch";
import CircularProgress from "@mui/material/CircularProgress"; // Import CircularProgress

const Community = () => {
  const forums = useFetchForums();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [forumItems, setForumItems] = useState([]);

  useEffect(() => {
    console.log("Forums from API:", forums); // Debugging line
    if (forums) {
      setForumItems(forums);
      setLoading(false);
    } else {
      setError("Failed to fetch forums.");
      setLoading(false);
    }
  }, [forums]);
  console.log(loading);
  console.log(error);

  if (loading) {
    return (
      <Layout>
        <div className="flex flex-col items-center">
          <CircularProgress /> {/* Display circular loading indicator */}
        </div>
      </Layout>
    );
  }

  if (error) {
    return (
      <Layout>
        <div className="flex flex-col items-center">
          <p>{error}</p>
        </div>
      </Layout>
    );
  }

  return (
    <Layout>
      <div className="flex flex-col items-center">
        {forumItems.map((forum, index) => (
          <Post forum={forum} key={index} /> // Added key prop
        ))}
      </div>
    </Layout>
  );
};

export default Community;

0 Answers0