11/14/2023

What is CORS

 CORS stands for Cross-Origin Resource Sharing. It is a security feature implemented by web browsers to control how web pages in one domain can request and interact with resources hosted on another domain.


In a web application, a web page often makes requests to a different domain for resources such as images, stylesheets, scripts, or data through XMLHttpRequest or Fetch API. However, due to the same-origin policy enforced by web browsers, these requests are typically restricted to the same domain for security reasons.


CORS allows a server to specify who can access its resources and under what conditions. It involves both server-side HTTP headers and client-side JavaScript APIs.


Here's a brief overview of how CORS works:


Client-Side (Browser): When a web page makes a cross-origin request using JavaScript (e.g., through XMLHttpRequest or Fetch API), the browser adds an "Origin" header to the request, indicating the origin (domain, protocol, and port) of the requesting site.


Server-Side (Server): The server then needs to handle this request and include appropriate CORS headers in the response. These headers include:


Access-Control-Allow-Origin: Specifies which origins are allowed to access the resource. It can be a specific origin, a comma-separated list of origins, or a wildcard (*) indicating that any origin is allowed.

Access-Control-Allow-Methods: Specifies the HTTP methods (e.g., GET, POST) that are allowed when accessing the resource.

Access-Control-Allow-Headers: Specifies which HTTP headers can be used when making the actual request.

Access-Control-Allow-Credentials: Indicates whether the browser should include credentials (like cookies or HTTP authentication) when making the actual request.

Access-Control-Expose-Headers: Specifies which headers should be exposed to the browser in the response.

Preflight Requests: For certain types of requests (e.g., those with certain methods or headers), the browser may send a preflight request (an HTTP OPTIONS request) to the server to check if the actual request is safe to send. The server responds with the appropriate CORS headers to indicate whether the actual request should proceed.


CORS is an important security feature that helps prevent malicious websites from making unauthorized requests on behalf of a user. It enables controlled sharing of resources across different origins while maintaining security on the web.

沒有留言: