How do I set up Angular to send the correct headers when making Cross Domain Ajax Requests?
What worked for me:
After about a full day of trying to find an answer to configuring my Angular application to work with CORS, I finally came up with a solution that works! Assuming you have set up the server correctly - the only thing you need to do on the client is delete the default header in your app config.
angular.module('myApp').config(['$httpProvider', function($httpProvider) {
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
The X-Requested-With header identifies the request as an AJAX request - and by default cross domain is not allowed. So all we need to do is remove it from our default settings and BOOM! It works.
For our application we are using a play backend(1.2.5) - The line of code we needed to add to make that work was:
Add headers to allow cross-domain requests. Be careful, a lot of browsers don't support these features and will ignore the headers. Refer to the browsers' documentation to know what versions support them.
Parameters: allowOrigin a comma separated list of domains allowed to perform the x-domain call, or "" for all. allowMethods a comma separated list of HTTP methods allowed, or null for all. allowCredentials Let the browser send the cookies when doing a x-domain request. Only respected by the browser if allowOrigin != ""
Http.Response.current().accessControl("*", "GET,PUT,POST,DELETE,OPTIONS",false);