CORS
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that defines how data can be securely shared between different domains.
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that defines how data can be securely shared between different domains.
Meta Title:
CORS (Cross-Origin Resource Sharing) – Definition, How It Works, and Security | Glossary
Meta Description:
Learn what CORS (Cross-Origin Resource Sharing) is, how it works in web browsers, and why it is essential for secure API communication.
Meta Keywords:
CORS, cross-origin resource sharing, web security, same-origin policy, api, browser, javascript
CORS (Cross-Origin Resource Sharing) is a security mechanism in web browsers that controls how resources (such as APIs or data) can be shared between different domains.
By default, browsers block cross-origin requests (for example, requests from example.com to api.otherdomain.com) due to the Same-Origin Policy, which helps prevent attacks like Cross-Site Request Forgery (CSRF).
CORS allows servers to explicitly specify via HTTP headers which domains, methods, or headers are permitted to access their resources.
domain-a.com tries to load data from api.domain-b.com.OPTIONS).Access-Control-Allow-Origin: https://domain-a.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors({ origin: "https://domain-a.com" }));
app.get("/data", (req, res) => {
res.json({ message: "CORS enabled for domain-a.com" });
});
app.listen(3000, () => console.log("Server running on port 3000"));
Access-Control-Allow-Origin: *) can create security risks.CORS is a central mechanism for secure and flexible web development. It enables controlled communication between different domains while protecting users from attacks.