AngularJS performs an OPTIONS HTTP request for a cross-origin resource

后端 未结 14 1379
生来不讨喜
生来不讨喜 2020-11-22 03:04

I\'m trying to setup AngularJS to communicate with a cross-origin resource where the asset host which delivers my template files is on a different domain and therefore the X

14条回答
  •  梦毁少年i
    2020-11-22 03:10

    For Angular 1.2.0rc1+ you need to add a resourceUrlWhitelist.

    1.2: release version they added a escapeForRegexp function so you no longer have to escape the strings. You can just add the url directly

    'http://sub*.assets.example.com/**' 
    

    make sure to add ** for sub folders. Here is a working jsbin for 1.2: http://jsbin.com/olavok/145/edit


    1.2.0rc: If you are still on a rc version, the Angular 1.2.0rc1 the solution looks like:

    .config(['$sceDelegateProvider', function($sceDelegateProvider) {
         $sceDelegateProvider.resourceUrlWhitelist(['self', /^https?:\/\/(cdn\.)?yourdomain.com/]);
     }])
    

    Here is a jsbin example where it works for 1.2.0rc1: http://jsbin.com/olavok/144/edit


    Pre 1.2: For older versions (ref http://better-inter.net/enabling-cors-in-angular-js/) you need to add the following 2 lines to your config:

    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
    

    Here is a jsbin example where it works for pre 1.2 versions: http://jsbin.com/olavok/11/edit

提交回复
热议问题