Header disallowed by preflight response

Explanation:

When making cross-origin AJAX requests, some browsers perform a preflight check to ensure that the intended requests are safe. This preflight request verifies that the server allows the specific HTTP headers and methods used in the actual request.

If the response from the server does not include the necessary CORS (Cross-Origin Resource Sharing) headers, the browser will block the actual request, resulting in a “header disallowed by preflight response” error.

To resolve this error, you need to configure the server to include the appropriate CORS headers in its responses. CORS headers include Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, etc.

For example:

Suppose you have a website hosted at https://www.example.com, and you want to make an AJAX request to retrieve data from an API hosted at https://api.example.com.

Step 1: On the server hosted at https://api.example.com, you need to include the following headers in the response:

Access-Control-Allow-Origin: https://www.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type

These headers indicate that the API at https://api.example.com allows requests from the website at https://www.example.com using the specified methods and headers.

Step 2: On your website, you can make the AJAX request using JavaScript or jQuery:

JavaScript:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    var response = JSON.parse(xhr.responseText);
    // Process the response
  }
};
xhr.send();

jQuery:

$.ajax({
  url: 'https://api.example.com/data',
  type: 'GET',
  dataType: 'json',
  headers: {
    'Content-Type': 'application/json'
  },
  success: function(response) {
    // Process the response
  },
  error: function(xhr, status, error) {
    // Handle the error
  }
});

By including the appropriate CORS headers on the server and making the AJAX request correctly, you can avoid the “header disallowed by preflight response” error and successfully retrieve data from the API.

Related Post

Leave a comment