Helena Standaert
Helena Standaert

Reputation: 569

AngularJS - Cross Origin Requests Blocked

I'm developing an AngularJS project and I'm working with an external Symfony REST api. However, my requests are blocked by Angular/JS. I did some research and added following lines to the config section of my app:

angular
.module('appName', [
  ....
])
.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];

..

However, firebug still throws an error: Cross Origin request blocked .. When I look into the 'NET' tab of firebug, this is what I get: NET tab screenshot

Any thoughts on this problem? Thanks in advance.

Upvotes: 1

Views: 3538

Answers (2)

Stan Sokolov
Stan Sokolov

Reputation: 2260

It did not work for me. After all things tried I created a PHP proxy page on my localhost that does the following

<?php echo file_get_contents($_REQUEST['url']); ?>

My angular controller calls the proxy

(function (){
    var app=angular.module('xxx',[]);

    app.controller('AdsController', ['$http', function($http)
    {
      var ads = this;
      ads.deals = [];
      $http.get('/proxy.php?url=whatvererurl'){
          ads.deals = data;
          console.log(ads.deals);
      });
    }]);

}
)();

just do not forget to encode URL

Upvotes: 0

Bogdan Savluk
Bogdan Savluk

Reputation: 6312

Looks like your symfony2 application returns inappropriate CORS headers in OPTIONS request response...

I am using symfony2 in conjunction with angularjs in few projects, and there is nothing special on angular side to make it work.

To return proper CORS headers I am using https://github.com/nelmio/NelmioCorsBundle in my symfony2 app.

There is configuration from dev server:

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: []
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['X-Requested-With','Content-Type','Authorization']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            allow_credentials: true
            max_age: 3600

Upvotes: 4

Related Questions