20

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);
4
  • Is there a question here? Commented Mar 14, 2013 at 14:21
  • 3
    no I just thought I would share since it took me a while to get this all set up correctly. Commented Mar 14, 2013 at 14:26
  • 2
    Reorganize your question to be a question, and post this as an answer. It may help others, but in its current format it may get closed. Commented Mar 14, 2013 at 14:31
  • 1
    Well, I see what you guys are saying, but thanks Dimitios - totally helped me! Commented May 20, 2013 at 23:07

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.