最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS - HTTP request makes preflight request in controllers but not in app.js - Stack Overflow

programmeradmin3浏览0评论

I have an app which municates with an external API. My app has a controller for each page. If I make a HTTP GET request in one of my controllers, it sends an OPTIONS preflight request, and I receive an error:

XMLHttpRequest cannot load http://dev/api/[email protected]&password=111111. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

However, if I copy paste the same code and paste it in my app.js file, it works flawlessly and returns me the data. I found out that this way it also only sends the GET request, and not the OPTIONS request.

I have tried adding the header content type as "text/plain" to my requests but that changes nothing. If I try making the requests with jQuery it works well, sending only the GET request, not matter if the code is in the controller or in the app.js file. Here is the plete controller code (in Angular form):

angular.module('website.homepage', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/', {
        templateUrl: 'homepage/view.html',
        controller: 'HomepageCtrl',
        resolve: {
            data: function($q, $http, $route, $rootScope) {
                var deferred = $q.defer();
                $http({method: 'GET', url: $rootScope.apiURL + 'home'})
                    .then(function(data) {
                        deferred.resolve(data);
                    });
                return deferred.promise;
            }
        }
    })
}])
.controller('HomepageCtrl', function ($scope, $http, data) {

        var url = "";

        $http({
            url: url,
            dataType: 'json',
            method: "GET",
            data: '',
            params: {
                email_address: '[email protected]',
                password: '111111'
            },
            headers: {
                'Content-Type': 'text/plain'
            }
        })
        .success(function(response) {
            console.log(response);

        })
       .error(function(response) {
            console.log(response);
       });


 })
 .config(function ( $httpProvider) {
     delete $httpProvider.defaults.headersmon['X-Requested-With'];
 })

I have an app which municates with an external API. My app has a controller for each page. If I make a HTTP GET request in one of my controllers, it sends an OPTIONS preflight request, and I receive an error:

XMLHttpRequest cannot load http://dev/api/[email protected]&password=111111. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

However, if I copy paste the same code and paste it in my app.js file, it works flawlessly and returns me the data. I found out that this way it also only sends the GET request, and not the OPTIONS request.

I have tried adding the header content type as "text/plain" to my requests but that changes nothing. If I try making the requests with jQuery it works well, sending only the GET request, not matter if the code is in the controller or in the app.js file. Here is the plete controller code (in Angular form):

angular.module('website.homepage', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/', {
        templateUrl: 'homepage/view.html',
        controller: 'HomepageCtrl',
        resolve: {
            data: function($q, $http, $route, $rootScope) {
                var deferred = $q.defer();
                $http({method: 'GET', url: $rootScope.apiURL + 'home'})
                    .then(function(data) {
                        deferred.resolve(data);
                    });
                return deferred.promise;
            }
        }
    })
}])
.controller('HomepageCtrl', function ($scope, $http, data) {

        var url = "http://dev.api";

        $http({
            url: url,
            dataType: 'json',
            method: "GET",
            data: '',
            params: {
                email_address: '[email protected]',
                password: '111111'
            },
            headers: {
                'Content-Type': 'text/plain'
            }
        })
        .success(function(response) {
            console.log(response);

        })
       .error(function(response) {
            console.log(response);
       });


 })
 .config(function ( $httpProvider) {
     delete $httpProvider.defaults.headers.mon['X-Requested-With'];
 })
Share Improve this question edited Oct 20, 2015 at 10:58 Luís Ferreira asked Oct 19, 2015 at 12:11 Luís FerreiraLuís Ferreira 2,6163 gold badges21 silver badges27 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

Have a research on the concept CORS which stands for Cross-Origin Resource Sharing. CORS is a technique by means of which resources on one location on the Internet are allowed to be requested from other domains. As a security feature, cross-origin requests are forbidden by default due to a notion known as same origin policy.

You are getting the error because you are trying to make a cross-origin request, which is, in fact, being disallowed.

Try to delete the header that Angular sends by default to prevent such requests:

angular.module('someModule') 
.config(function ( $httpProvider) {        
    delete $httpProvider.defaults.headers.mon['X-Requested-With'];
})...

Update

I think, there can be only one configuration block in a module. Therefore, you need to bine the two configurations you have into a single one:

angular.module('website.homepage', ['ngRoute'])
.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) { // inject the other provider here
$routeProvider.when('/', {
    templateUrl: 'homepage/view.html',
    controller: 'HomepageCtrl',
    resolve: {
        data: function($q, $http, $route, $rootScope) {
            var deferred = $q.defer();
            $http({method: 'GET', url: $rootScope.apiURL + 'home'})
                .then(function(data) {
                    deferred.resolve(data);
                });
            return deferred.promise;
        }
      }
    });

    delete $httpProvider.defaults.headers.mon['X-Requested-With'];
}])...   // rest of your code (services, factories, whatever)
发布评论

评论列表(0)

  1. 暂无评论