Angular resource how to keep ajax header and enable cors at the same time Angular resource how to keep ajax header and enable cors at the same time angularjs angularjs

Angular resource how to keep ajax header and enable cors at the same time


If you are using the latest version of angular.js, you can do this

First, add xhr header (what you did was correct)

    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

Then in your google map search function

var searchAddress = function(address) {    var params = {address: address, sensor: false};    //Note: google map rejects XHR header    $http.get(google_map_web_api_url, {params: params, headers: {'X-Requested-With': undefined}})        .success(function(data, status, headers, config) {        })        .error(function(data, status, headers, config) {        })}

The headers config argument passed in will delete xhr per request base, which means your ng-resource requests are untouched


Setting custom headers on XHR requests triggers a preflight request.

So, it doesn't disable CORS but your server is most likely not handling the preflight request.

Inspired from this post: https://remysharp.com/2011/04/21/getting-cors-working

The solution should be to use the cors module and add the following to your node.js code before your routes:

var corsOptions = {    origin: true,    methods: ['GET', 'PUT', 'POST'],    allowedHeaders: ['X-Requested-With','Content-Type', 'Authorization']};app.options('*', cors(corsOptions)); //You may also be just fine with the default options

You can read more at: https://github.com/expressjs/cors