reactjsexpressfrontendcors

CORS error using react and express after setting up cors in express


I configured my server like below.

app.use(cors({
  origin: 'http://localhost:5173', // Allow requests from your frontend
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // Specify allowed methods
  credentials: true // Allow cookies to be sent
}));

I used passport.js to help with authentication. I click sign in, gets redirected to google sign in, after signed in, i get redirected to my client home page. Then I would fetch the authenticated user from backend. When i am first redirected to my client home page, console will log cors error, access control allow origin value is set to my backend, Error message, Error Response Header but the interesting thing happens when i refresh the web page, the cors error will disappear. And when i check the network request, now the access control allow origin value is correct. network tab after i refresh the page

I have spent the last two days trying to figure out what is happening and i made 0 progess.

I have cors run before my routes. I looked up on the web, used gpt, looked through my code base, no progress.


Solution

  • I had a similar issue recently. Here’s what worked for me: I installed the cors package by running npm i cors. Then, I imported it and configured it in my server file like this:

    app.use(cors({ origin: 'http://localhost:5173' }));
    

    In my setup, the Node server was running on port 3000, while React was on port 5173. Alternatively, you can set up a proxy server in Vite. To do this, add the following to your vite.config.js file:

    server: {
     proxy: {
       '/api': {
       target: "http://localhost:3000"
       }
     }
    }