CORS (Cross-Origin Resource Sharing) is a security feature implemented by web browsers to control how resources can be requested from a different domain (origin) than the one from which the resource originated. It is crucial in modern web development, especially when working with APIs, as it prevents unauthorized access to resources and ensures a secure exchange of data.
An origin is defined by the combination of:
Example:
The Same-Origin Policy is a security measure that restricts how resources on a web page can interact with resources from another origin.
While SOP ensures security, it limits legitimate cross-origin requests, which is where CORS comes in.
CORS is a mechanism that allows servers to specify who can access their resources by including specific HTTP headers in their responses. These headers indicate whether the browser should allow the client to access the requested resources.
When a browser makes a cross-origin request, it checks the server's response headers to determine whether the request is allowed.
Key Steps:
Preflight Request (Optional):
For certain types of requests, the browser sends an initial OPTIONS request to check if the actual request is permitted.
Server Response:
The server includes appropriate CORS headers in the response.
Browser Decision:
If the headers match the browser's expectations, the resource is shared; otherwise, the browser blocks the request.
Access-Control-Allow-Origin: Specifies which origins are allowed to access the resource.
Example: Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: Specifies the HTTP methods that are allowed.
Example: Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Specifies the custom headers that can be sent in requests.
Example: Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: Indicates whether credentials (cookies, HTTP authentication) can be sent.
Example: Access-Control-Allow-Credentials: true
Simple Requests:
Preflighted Requests:
Credentialed Requests:
fetch("https://api.otherdomain.com/data", { method: "GET", headers: { "Content-Type": "application/json", }, credentials: "include", // For sending cookies or credentials }) .then(response => response.json()) .then(data => console.log("Data:", data)) .catch(error => console.error("Error:", error));
Access-Control-Allow-Origin: https://example.com Access-Control-Allow-Methods: GET, POST Access-Control-Allow-Headers: Content-Type, Authorization Access-Control-Allow-Credentials: true
const express = require("express"); const cors = require("cors"); const app = express(); // Use the CORS middleware app.use(cors({ origin: "https://example.com", // Allow only this origin methods: ["GET", "POST"], // Allow these HTTP methods credentials: true, // Allow credentials })); app.get("/data", (req, res) => { res.json({ message: "CORS request successful" }); }); app.listen(3000, () => console.log("Server running on port 3000"));
Error: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Error: Credentialed requests require 'Access-Control-Allow-Credentials' to be true.
Preflight Request Fails:
CORS is a vital feature for secure and functional cross-origin resource sharing in web applications. By understanding and properly configuring CORS headers on your server, you can ensure smooth and secure communication between domains while adhering to web security standards.
Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.
The above is the detailed content of Understanding CORS: Secure Cross-Origin Resource Sharing in JavaScript. For more information, please follow other related articles on the PHP Chinese website!