The pain of handling CORS headers

This is a sort of collection of all real-life issues that make usage of cross-origin ajax such a pain the ass.

Favorite reference is the MDN page.

The crucial points are:

  • the server response headers must always mention the OPTIONS method, otherwise all preflighted requests will fail silently
  • using the Authorisation header in the request triggers the preflight
  • client code must explicitly set xhr.withCredentials = true
  • server code must explicitly mention the domains from where it expects to receive requests with credentials
  • if the server uses wildcards in the Access-Control-Allow-Origin header, they will be held valid only for client requests that do not send credentials
  • what else?

Example of client code (

   url: '',
   type: 'GET',
   dataType: 'json',
   data: data,
   crossDomain: true,
   xhrFields: { withCredentials: true },
   headers: { 
     "Authorization":"Basic " + btoa(username + ":" + password),
   success: function(data) { bla bla }

Example of PHP client code (

  $response->header('Access-Control-Allow-Origin', '');
  $response->header('Access-Control-Allow-Methods', 'GET, OPTIONS, HEAD');
  $response->header('Access-Control-Allow-Headers', 'Authorization');
  $response->header('Access-Control-Allow-Credentials', 'true');

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s