This article, peer-reviewed by Panayiotis "pvgr" Velisarakos (with thanks to all SitePoint peer reviewers!), explores Cross-Origin Resource Sharing (CORS), an HTML5 API enabling websites to access previously restricted external resources. CORS relaxes the same-origin policy, allowing requests to different domains. For instance, before CORS, cross-domain AJAX requests were impossible. This article demonstrates how CORS enhances web experiences.
Key Takeaways:
Access-Control-Allow-Origin
header determines which origins can access server responses.Access-Control-Allow-Credentials
header controls cookie access.crossorigin
attribute (with anonymous
or use-credentials
values) controls credential handling for <img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173984767246953.jpg" class="lazy" alt="An In-depth Look at CORS "><code><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173984767246953.jpg" class="lazy" alt="An In-depth Look at CORS ">
<p><strong>Preflights:</strong></p>
<p>For complex requests (methods beyond GET/HEAD/POST, or custom headers), preflights (an initial OPTIONS request) verify server acceptance. The server responds with <code>Access-Control-Allow-Origin
Access-Control-Allow-Credentials
Access-Control-Allow-Methods
Preflights:Access-Control-Allow-Headers
Access-Control-Max-Age
Access-Control-Request-Method
For complex requests (methods beyond GET/HEAD/POST, or custom headers), preflights (an initial OPTIONS request) verify server acceptance. The server responds with Access-Control-Request-Headers
, , , , and
and in the preflight.
Access-Control-Allow-Origin
img.setAttribute('crossOrigin', 'anonymous');
in server configuration). The client-side code requires . Without CORS, a security exception occurs.crossorigin
crossorigin
Origin
The anonymous
Attribute:use-credentials
Access-Control-Allow-Credentials: true
attribute triggers a CORS request with the header. omits credentials;
includes them (requiring server-side ). Conclusion:CORS significantly enhances web development by facilitating cross-origin resource access. It's crucial to understand its security implications and implement it correctly.
Frequently Asked Questions (FAQs):
The FAQs section provides detailed answers to common questions about CORS, covering the purpose of headers, cookie handling, simple vs. preflighted requests, server-side configuration, security risks, HTTP request compatibility, the role of specific headers, browser behavior, testing, and the differences between CORS and JSONP. (The original FAQ section is retained in its entirety.)
The above is the detailed content of An In-depth Look at CORS. For more information, please follow other related articles on the PHP Chinese website!