skip to Main Content

I am working on a app using reactJS and nodeJS.

It’s simply a connection to a database and I am trying to retrieve a row. My connection to the database is fine. But I am unable to solve the cors error I am getting.
This is the error Access to fetch at 'http://localhost:3000/infos' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

NodeJS is running on 3000, and if I navigate to http://localhost:3000/infos I see my info returned just fine, but running my reactJS program (which is on port 3001) I get the error cause my program is trying to get the data from port 3000.
I have read alot of other answers and saw it suggested to use the following,

  origin: "http://localhost:3001", // Allow requests from your React app
}));

but this has not solved my problem. I have added my code to see if anyone could see what was the issue.

This is my server .js code.

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");  
const { connectToDB, closeDB } = require("./db_connect");  

const app = express();
const port = 3000;

app.use(bodyParser.json());

 
app.use(cors({
  origin: "http://localhost:3001",  
}));
 
app.get("/infos", async (req, res) => {
  try {
    const pool = await connectToDB(); 
    const result = await pool.request().query("SELECT * FROM  Information");
    res.json(result.recordset);
  } catch (err) {
    console.error("Error fetching information:", err);
    res.status(500).json({ error: "Server error" });
  }
});

 
process.on("SIGINT", async () => {
  try {
    await closeDB(); 
    process.exit(0);
  } catch (err) {
    console.error("Error closing the database connection:", err);
    process.exit(1);
  }
});
 
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

and this is my app.js code.

import logo from './logo.svg';
import './App.css';

import React, { useState, useEffect } from "react";

function App() {
  const [info, setInfos] = useState([]);

  useEffect(() => {
    // Fetch data from the backend API endpoint
    fetch("http://localhost:3000/infos")
      .then((response) => response.json())
      .then((data) => setInfos(data))
      .catch((error) => console.error("Error fetching data:", error));
  }, []);

  return (
    <div>
      <h1>Information</h1>
      <ul>
        {infos.map((info) => (
          <li key={info.id}>
            {info.firstName} {info.lastName} - No.: {info.Number}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

2

Answers


  1. You will need to set ‘Access-Control-Allow-Origin’ in ‘res’ variable to enable cors before try inside the app.get function.

    Below is the code you can use.

    app.get("/infos", async (req, res) => {
      res.set('Access-Control-Allow-Origin', '*');
      try {
         const pool = await connectToDB(); 
         const result = await pool.request().query("SELECT * FROM  Information");
         res.json(result.recordset);
      } catch (err) {
         console.error("Error fetching information:", err);
         res.status(500).json({ error: "Server error" });
      }
    });
    
    Login or Signup to reply.
  2. You can do it either way….
    Option 1:Allowing Your Response for origins

    res.set('Access-Control-Allow-Origin', '*');
    

    Option 2: Allowing whole app to user origins without specifying explicit origins

    app.use(cors());
    

    Note: Both of them depends on requirement of your applications.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search