Sobes.tech
Junior — Middle

Can you explain what the term CORS means and how it works in the context of web development?

sobes.tech AI

Answer from AI

CORS (Cross-Origin Resource Sharing) is a security mechanism in web development that allows restricting or permitting web pages to access resources from another domain.

By default, browsers block scripts on one page from making requests to a different domain (same-origin policy) to prevent attacks like Cross-Site Request Forgery (CSRF).

CORS works as follows:

  • When a browser makes a request to another domain (cross-origin request), it sends a special Origin header indicating the source of the request.
  • The server, upon receiving the request, checks this header and, if it allows access, responds with an Access-Control-Allow-Origin header specifying which domains can access the resources.
  • If the response contains the allowing header, the browser permits the script to access the data.
  • In some cases (e.g., with non-standard methods or headers), the browser first sends a "preflight" OPTIONS request to check permissions.

Thus, CORS enables servers to control who can access their resources from a browser, balancing security and functionality.