The Issue
While developing my CampusX project, I ran into a frustrating bug:
β
Frontend (React) was calling the backend (Express).
β But I kept getting a CORS policy error in the browser console.
What is CORS?
CORS (Cross-Origin Resource Sharing) is a security feature in browsers that blocks requests from a different origin unless the server explicitly allows them.
In my case:
-
Frontend:
http://localhost:3000
-
Backend:
http://localhost:5000
- The browser blocked the request because the backend didn't allow requests from the frontendβs origin.
The Root Cause
I hadnβt properly configured CORS middleware in my Express backend.
const express = require("express");
const cors = require("cors");
const app = express();
// β No CORS setup -> Browser blocks cross-origin requests
app.use(express.json());
app.listen(5000, () => console.log("Server running on port 5000"));
The Fix
I installed the cors package and added this middleware:
npm install cors
Then, in server.js (or app.js), I added:
app.use(cors({
origin: "http://localhost:3000", // Allow frontend requests
credentials: true, // Allow cookies & authentication headers
}));
Now, my frontend could successfully communicate with the backend without CORS issues. π
β Option 2: Handling CORS for Production
For production, I replaced localhost:3000 with the actual frontend URL:
const allowedOrigins = ["http://localhost:3000", "https://campusx.com"];
app.use(cors({
origin: allowedOrigins,
credentials: true,
}));
This ensures the backend only allows requests from trusted domains.
Key Takeaways
- CORS errors happen when the frontend and backend run on different origins.
- Use the cors middleware in Express to allow frontend requests.
- Always enable credentials: true if using cookies for authentication.
Top comments (0)