Junior — Middle
Can you explain what Cross-Origin headers mean and why they are needed in web development?
sobes.tech AI
Answer from AI
Cross-Origin (CORS — Cross-Origin Resource Sharing) headers are used to control access to web server resources from other domains (origins). By default, browsers block requests from one domain to another for security reasons (same-origin policy).
CORS headers allow the server to explicitly specify which external domains can access its resources and which HTTP methods are permitted.
Main headers:
Access-Control-Allow-Origin— specifies which domains are allowed access.Access-Control-Allow-Methods— which HTTP methods are allowed (GET, POST, etc.).Access-Control-Allow-Headers— which headers are allowed in the request.
For example, if the frontend at https://example.com makes a request to an API at https://api.example.org, the server should return the header:
Access-Control-Allow-Origin: https://example.com
Otherwise, the browser will block the response.
Thus, CORS ensures secure data exchange between different sources in web applications.