Successful CORS configuration with AngularJS 1.2 and WordPress

Some thoughts on a successful CORS (Cross Origin Request Sharing) setup while interrogating a remote REST API on Wordpress with AngularJS 1.2.


I'm developing an hybrid mobile app with AppGyver Steroids - based on PhoneGap - and a WordPress backend. The architecture is the usual Web stuff: make XHR from the mobile app to a REST API. Since the mobile app is on a different domain/server/port from the mobile app, you run into the classic Same Origin Policy problem.

I've been struggling to configure both WordPress and AngularJS to behave correctly. Particularly with Angular which online resources are IMHO wrong about how to deal with this problem.

Read this first for some excellent CORS context: Using CORS tutorial.


I'm using the WP-API Plugin to serve WordPress content via a REST API, but it's almost irrelevant since you don't have to modify the plugin. The magic happens in WordPress .htaccess:

CORS Headers

The first part (headers) allows you to specify the HTTP headers needed for CORS to work. In my case (development setup), I allow remote access to all the site from all origin on all methods. Please do not use it as is on production.

An important thing to note: you have to make sure you send back to the client every Access-Control-Request-* headers it sends in the form of Access-Control-Allow-* headers with the same value (or the desired filtered value). I was missing Content-Type at first and was stuck for a while... Inspect your client requests in Firebug and build you server response accordingly.

OPTIONS method

Following the CORS protocol, the browser that does a Cross Origin Request first hits the server with the OPTIONS method to make sure it is CORS-enabled before sending the real request (POST, PUT...). Since WordPress does not know about the OPTIONS method, someone in the WP-API issue queue came up with a hack (not pretty IMHO but works): always return a 200 OK response when hit by a OPTIONS method. Radical.


There is absolutely nothing to do on the Angular side!! You may read here and there that you have to add stuff like this in your app config:

Don't! Maybe it was useful for older versions of Angular or for very special backends, but from my experience you do not need this. Especially the httpProvider.defaults.useXDomain option which does not even exist (look at angular.js code)!

Alexandre Bulté avatar
Écrit par Alexandre Bulté
en web,angularjs,wordpress
blog comments powered by Disqus
Fork me on GitHub