Middle
Tell about CORS: what is it for, what headers are used?
sobes.tech AI
Answer from AI
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that allows controlling access of web pages to resources from another domain.
It is used to prevent unauthorized requests between different sources (domains, ports, protocols).
Main CORS headers:
- Access-Control-Allow-Origin — specifies which domains are allowed access to the resource.
- Access-Control-Allow-Methods — which HTTP methods are permitted (GET, POST, PUT, etc.).
- Access-Control-Allow-Headers — which headers the client can use in the request.
- Access-Control-Allow-Credentials — allows sending cookies and authentication data.
- Access-Control-Expose-Headers — which headers are accessible to the client.
- Access-Control-Max-Age — the duration for which the result of the cross-origin request check is cached.
Example:
If the frontend on example.com makes a request to api.example.org, the server at api.example.org should include in its response:
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET, POST
This will allow the browser to permit the request.