HTTP request from Angular sent as OPTIONS instead of POST
When debugging Cross-Origin Resource Sharing (CORS) issues, it is common to encounter a scenario where your browser logs show an OPTIONS request failing before your actual POST ever executes. This often leaves developers confused about why the payload isn't reaching the server and why the HTTP status code returned during the preflight check is 400 Bad Request rather than the expected 200 OK.
The root cause lies in how modern browsers enforce security policies. Before sending a non-simple requestâsuch as a POST with custom headers like Content-Type: application/json or specific custom headers like fooâthe browser intercepts the call and sends an OPTIONS "preflight" request to the target server. This handshake allows the server to confirm that it is willing to accept the actual request on behalf of the origin domain.
In your specific case, the Angular code you provided correctly initiates a POST request:
$http({
method: 'POST',
url: api_endpoint + 'test',
headers: {
'foo': 'value',
'content-type': 'application/json'
},
data: { bar:'value' }
});
However, the error message XMLHttpRequest cannot load ... Response for preflight has invalid HTTP status code 400 indicates that your PHP script rejected this initial OPTIONS handshake. You have correctly added headers to allow CORS, but the browser is not interpreting them as valid because they are missing one critical piece of information required by the specification: the Access-Control-Allow-Credentials header or the specific handling of the request method depending on your configuration.
The most frequent oversight in this scenario involves how the server responds to the OPTIONS verb itself. While you have listed POST, GET, DELETE, and PUT in your Access-Control-Allow-Methods, the browser expects the server to explicitly acknowledge the methods allowed for preflight requests or, more commonly, simply return a 200 status with the appropriate headers when it receives an OPTIONS request.
If your PHP script treats the incoming OPTIONS request as if it were a standard request and attempts to process it through your application logic without specific handling, it might return a 400 error or redirect, causing the browser to abort the connection immediately. To resolve this, you must ensure that when an OPTIONS request is received, the server responds with a 200 status code and includes all necessary CORS headers.
Here is how you should structure your PHP response to handle preflight requests robustly:
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
header('Access-Control-Allow-Origin: *');
// If credentials are used, set this to true and restrict Access-Control-Allow-Origin accordingly
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding, X-Auth-Token');
header('Access-Control-Max-Age: 86400'); // Cache the preflight result for one day
// It is crucial to stop further script execution here for OPTIONS requests
exit(0);
}
// Continue with your normal POST logic below
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Handle your actual POST request logic
}
Notice the use of exit(0) after sending headers for the OPTIONS method. This prevents the server from attempting to render a response body or execute further logic that might inadvertently alter the status code or headers, which could confuse the browser. Additionally, if you intend to send cookies or authenticated tokens with your Angular requests (indicated by the Authorization header in your list), you must ensure that Access-Control-Allow-Credentials: true is set. However, when credentials are required, you cannot use Access-Control-Allow-Origin: *; instead, you must specify the exact origin (e.g., http://localhost:4200) to avoid security violations.
The discrepancy you observed between local (localhost) and remote servers likely stems from how your development environment or specific proxy configurations handle these headers differently compared to production. Ensure that any reverse proxies or load balancers in your stack are not stripping these headers before they reach your PHP backend. By strictly handling the OPTIONS verb at the entry point of your application and ensuring a clean 200 response with all headers intact, the preflight check will succeed, allowing your Angular application to proceed with the actual POST data submission.
