How to fix standard CORS Policy errors in React and Node.js
How to Fix CORS Errors in React and Node.js
If you're building a full-stack application, odds are you've encountered this infamous error in your browser console:
Access to fetch at 'http://localhost:5000/api/data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This happens because browsers have a security feature called Same-Origin Policy. It prevents a malicious script on one page from obtaining access to sensitive data on another web page.
The Solution (Node.js/Express Backend)
The easiest way to fix this is to enable CORS on your backend.
-
Install the
corspackage:npm install cors -
Add it to your Express app:
const express = require('express'); const cors = require('cors'); const app = express(); // Enable All CORS Requests app.use(cors()); // Or enable it for a specific origin: // app.use(cors({ origin: 'http://localhost:3000' }));
By setting the proper headers, your browser will now allow the cross-origin request to succeed!
Alternative Solutions (Frontend Proxy)
If you cannot modify the backend, you can set up a proxy in your React app.
In vite.config.js:
export default defineConfig({
server: {
proxy: {
'/api': 'http://localhost:5000'
}
}
})
This makes your frontend server proxy the requests, avoiding the browser CORS check entirely.