javascriptreactjsaxios

Facing errors in fetching data from rest API to my front-end


I am trying to fetch data from my rest api to my react front-end and i'm getting some errors like

This image contains all the errors i'm facing

My server is running on "http://localhost:5000"

Home.jsx -> I've to fetch data here and console.log it

import { useEffect, useState } from "react";
import Header from "../../components/header/Header";
import Posts from "../../components/posts/Posts";
import Sidebar from "../../components/sidebar/Sidebar";
import "./home.css";
import axios from "axios";

const Home = () => {
  const [posts, setposts] = useState([]);

  const fetchPosts = async () => {
    try {
      const res = await axios.get("http://localhost:5000/api/posts");
      console.log(res.data);
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    fetchPosts();
  }, []);

  return (
    <>
      <Header />
      <div className="home">
        <Posts />
        <Sidebar />
      </div>
    </>
  );
};

export default Home;

I've checked my server is running and the url is also correct as it is giving back data when i'm requesting data from it in postman.

Server.js -> CORS is added in my server code

const dotenv = require("dotenv");
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const authRoute = require("./routes/auth");
const userRoute = require("./routes/users");
const postRoute = require("./routes/posts");
const categoryRoute = require("./routes/categories");

dotenv.config();
app.use(express.json());

const cors = require("cors");
app.use(cors());

mongoose
  .connect(process.env.MONGO_URL)
  .then(() => {
    console.log("Connect to database");
  })
  .catch((err) => {
    console.log(err);
  });


app.use("/api/auth", authRoute);
app.use("/api/users", userRoute);
app.use("/api/posts", postRoute);
app.use("/api/categories", categoryRoute);

app.listen(process.env.PORT, () => {
  console.log("Server is running on port: " + process.env.PORT);
});

Solution

  • I see that your React frontend is running on port 3000 and your API is running on port 5000. Because of this difference, your browser sees the request to the API as a cross origin request and has blocked it according to its CORS Policy.

    While developing the application, you could turn off your browser's secutiy so it will not block cross origin requests.

    When you build your app, you can avoid cross origin requests by serving your frontend from your API, so that only one server is serving your frontend and data from your API. To do this, you need to build the frontend and serve the files as static files from your server, then route any URL with /api to your API, and serve your app from the top level route (/).

    In Express.js, it looks something like the following:

    import routes from "./routes"
    
    const frontendPath = path.resolve(__dirname, "..", "..", "frontend", "dist");
    
    // Routes
    // catch any routes with prefix /api
    app.use("/api", routes)
    // api route that does not resolve
    app.use(/\/api\/.*/, (req: Request, res: Response) => {
        res.status(404).json({ status: "error", message: `Could not find ${req.originalUrl}` });
    })
    
    // Frontend
    // pass all routes that do not contain /api to the frontend
    app.use(express.static(frontendPath))
    app.use((_, res) => {
        res.sendFile(path.join(frontendPath, "index.html"))
    })
    

    Where routes is a collection of routes defined in another file.