What is CORS
What is CORS and why is it important in web development?
CORS (Cross-Origin Resource Sharing) is a mechanism that defines how a browser should allow or block requests from different domains. If your front-end and back-end are on different origins (e.g., different domains or ports), you will inevitably encounter CORS-related issues.
For example, if you create a React app running on http://localhost:3000
and your API is on http://localhost:5000
, the browser will check whether the request is allowed under CORS policies when you try to fetch data.
Two origins are considered different if any of the following vary:
Examples:
http://example.com
and http://api.example.com
→ different originshttp://localhost:3000
and http://localhost:5000
→ different originsWhen a browser makes a cross-origin request, it first sends a "preflight" request using the HTTP OPTIONS
method. This allows the server to respond whether requests from that origin are permitted.
The server must send appropriate headers in its response, such as:
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
If these headers are missing or incorrect, the browser will block the request, even if the server technically responded.
// Express.js backend
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors({
origin: "http://localhost:3000", // allow only this origin
methods: ["GET", "POST", "PUT", "DELETE"],
credentials: true
}));
app.get("/data", (req, res) => {
res.json({ message: "Hello from the frontend!" });
});
app.listen(5000, () => console.log("Server is running on port 5000"));
Advantages of this setup:
credentials: true
and include the appropriate headers.CORS is a security mechanism that controls which origins can access your APIs. While it may be frustrating during development, proper configuration ensures security and prevents unauthorized access.
By using the correct Access-Control-Allow-*
headers, you can enable secure and efficient interaction between your front-end and back-end systems.