CORS: Preflighting HTTPRequests
Cross-Origin Resource Sharing (CORS) poses limitations on cross-domain HTTP requests. To address these challenges, preflight requests can be employed. In this context, preflight requests involve sending an OPTIONS request to the server before the actual request is made. This allows the server to verify that the request is allowed and to provide the necessary permissions.
How to Preflight a Request
Preflighting an HTTP request involves sending an OPTIONS request with specific headers, indicating the desired method and headers for the actual request. The server responds with headers granting or denying the request permissions.
Server-Side Preflight Response
The server should respond to preflight requests with the following headers:
Client-Side Preflight Request
In jQuery, the following technique can be used to preflight a request:
<code class="javascript">$.ajax({ url: yourUrl, type: 'OPTIONS', success: function(data, status) { // Extract and verify the preflight response headers var origin = data.getResponseHeader('Access-Control-Allow-Origin'); var methods = data.getResponseHeader('Access-Control-Allow-Methods'); var headers = data.getResponseHeader('Access-Control-Allow-Headers'); // Proceed with the actual request only if permissions are granted if (origin === 'http://mydomain.com' && methods.indexOf('POST') !== -1 && headers.indexOf('X-Custom-Header') !== -1) { // Make the actual request } else { // Handle the error and deny the request } } });</code>
By implementing these changes, you can ensure that your cross-domain HTTP requests are preflight-verified and can proceed without browser intervention.
The above is the detailed content of How to Preflight an HTTP Request for Cross-Origin Resource Sharing (CORS)?. For more information, please follow other related articles on the PHP Chinese website!