Understanding CORS - Cross-Origin Resource Sharing

Jul 9, 2024

CORS - Cross Origin Resource Sharing

Overview

  • Presenter: Akshan
  • Topic: CORS (Cross-Origin Resource Sharing)
  • Focus: Explanation of CORS, browser handling, preflight mechanisms, common errors, and interview questions.

What is CORS?

  • Definition: A mechanism using additional HTTP headers to control resource sharing between web apps of different origins.
  • Importance: Allows sharing resources across different origins, subdomains, ports, and protocols.
  • Prior to standardization, browsers did not allow resource sharing across different origins (e.g., domain, subdomain, port, protocol).
  • Example: akshaysaini.in accessing google.com/api/get-data.

Cross-Origin Definition

  • Domain: The main address (e.g., akshaysaini.in).
  • Subdomain: Part of the primary domain (e.g., api.akshaysaini.in).
  • Port: Different endpoints (e.g., akshaysaini.in on port 5050).
  • Protocol: HTTP vs HTTPS.

How CORS Works

  • Browser Mechanism: Uses additional HTTP headers for verification.
  • Preflight: Preflight request (OPTIONS call) is made before the actual request.
  • Server Role: Verifies the request and sets HTTP headers.
  • Example: Application A (Origin 1) requests data from Application B (Origin 2).

Preflight Mechanism

  • Preflight Request: Browser makes an OPTIONS call before the actual API call.
  • Server Verification: Server B verifies and responds with HTTP headers.
  • Actual Call: Made only if preflight is validated.

Important HTTP Headers

  • Access-Control-Allow-Origin: Specifies allowed domains. Values can include * for all domains or specific domains (e.g., google.com).
  • Access-Control-Allow-Methods: Specifies allowed methods (GET, POST, PUT, DELETE).
  • Others: Varies as needed.

Types of Requests

  • Simple Requests: Do not require preflight (actual call made directly).
  • Preflight Requests: Require preflight due to complexity (must meet specific criteria).
  • Criteria: Defined by the browser, refer to MDN documentation for details.

Handling CORS Errors

  • Common Error: Access-Control-Allow-Origin header missing.
  • Browser Behavior: Expected, as it's a security feature.
  • Resolution: Set appropriate headers on the server.
  • Development Tips: Avoid bypassing CORS security with plugins or Chrome flags (e.g., --disable-web-security). Follow web standards.

Browser Support

  • Support: All major browsers support CORS. Refer to MDN for a full list.

CORS in Interviews

  • Importance: Hot topic in interviews, especially for developers working on large-scale applications.
  • Preparation Tips: Study common questions, scenarios, and additional details using MDN documentation.

Conclusion

  • Summary: Covered CORS definition, important concepts, and examples.
  • Stay Updated: Subscribe to the channel, and enable notifications for future videos.

  • Feedback: Appreciate likes, subscriptions, and comments.