Home  >  Article  >  Web Front-end  >  How to Preflight an HTTP Request for Cross-Origin Resource Sharing (CORS)?

How to Preflight an HTTP Request for Cross-Origin Resource Sharing (CORS)?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-18 21:54:31936browse

How to Preflight an HTTP Request for Cross-Origin Resource Sharing (CORS)?

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:

  • Access-Control-Allow-Origin: The domain that is allowed to make the actual request.
  • Access-Control-Allow-Methods: The allowed methods for the actual request.
  • Access-Control-Allow-Headers: The allowed headers for the actual request. This header cannot be '*'.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn