Search code examples
angularjshttppostangular-resource

What is the best way to avoid sending OPTIONS (preflight) using $resource in AngularJS


I am making a simple webapp that is communicating with a server that I have no control over.

At first I configured a custom $resource GET request and that worked fine. Now I need to do a POST request to request some information from the same server. This dind't work at all since it seems the server does not have the Access-Control-Allow-Origin header set for OPTIONS but it does for GET and POST. Knowing this I found that I can do (found this in another post):

app.config(['$httpProvider', function ($httpProvider) {
//Reset headers to avoid OPTIONS request (aka preflight)
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
}]);

This works fine but it seems a bit like an ugly hack to me and I wonder how to do it in a better way.


Solution

  • After A LOT of searching for an answer it turn out that all you have to do is to set the Content-Type header to text/plain in order to avoid the OPTIONS request/preflight. You do this for a custom action like this:

    $resource('yourURL', {}, {
        customAction: {method:'POST', headers:{'Content-Type':'text/plain'}}
    });
    

    I didn't have to change anything except this to make it work.