How to skip the OPTIONS preflight request?

Bram Vandewalle picture Bram Vandewalle · Apr 9, 2014 · Viewed 118.4k times · Source

I had developed a PhoneGap app which is now being transformed to a mobile website. Everything works smoothly besides one small glitch. I use a certain third party API via a POST request, which works fine in the app, but fails in the mobile website version.

After a closer look it seems like AngularJS (I guess the browser actually) is first sending an OPTIONS request. I learned a lot today about CORS, but I can't seem to figure out how to disable it altogether. I do not have access to that API (so changes at that side are impossible), but they have added the domain I am working on to their Access-Control-Allow-Origin header.

This is the code I am talking about:

        var request = {
                language: 'fr',
                barcodes: [
                    {
                        barcode: 'somebarcode',
                        description: 'Description goes here'
                    }
                ]
            };
        }
        var config = {
            headers: { 
                'Cache-Control': 'no-cache',
                'Content-Type': 'application/json'
            }
        };
        $http.post('http://somedomain.be/trackinginfo', request, config).success(function(data, status) {
            callback(undefined, data);
        }).error(function(data, status) {
            var err = new Error('Error message');
            err.status = status;
            callback(err);
        });

How can I prevent the browser (or AngularJS) from sending that OPTIONS request and just skip to the actual POST request? I am using AngularJS 1.2.0.

Thanks in advance.

Answer

Ray Nicholus picture Ray Nicholus · Apr 9, 2014

The preflight is being triggered by your Content-Type of application/json. The simplest way to prevent this is to set the Content-Type to be text/plain in your case. application/x-www-form-urlencoded & multipart/form-data Content-Types are also acceptable, but you'll of course need to format your request payload appropriately.

If you are still seeing a preflight after making this change, then Angular may be adding an X-header to the request as well.

Or you might have headers (Authorization, Cache-Control...) that will trigger it, see: