简体   繁体   English

AngularJS-HTTP请求在控制器中发出预检请求,但不在app.js中

[英]AngularJS - HTTP request makes preflight request in controllers but not in app.js

I have an app which communicates with an external API. 我有一个与外部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: 如果我在一个控制器中发出HTTP GET请求,它会发送一个OPTIONS预检请求,并且会收到错误消息:

XMLHttpRequest cannot load http://dev/api/?email_address=email@email.com&password=111111 . XMLHttpRequest无法加载http:// dev / api /?email_address=email@email.com&password=111111 Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response. 请求标头字段在飞行前响应中,Access-Control-Allow-Headers不允许进行授权。

However, if I copy paste the same code and paste it in my app.js file, it works flawlessly and returns me the data. 但是,如果我复制粘贴相同的代码并将其粘贴到我的app.js文件中,则它可以正常工作并返回数据。 I found out that this way it also only sends the GET request, and not the OPTIONS request. 我发现以这种方式它也只发送GET请求,而不发送OPTIONS请求。

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. 如果我尝试使用jQuery进行请求,那么它会很好地工作,仅发送GET请求,而无论代码是在控制器中还是在app.js文件中。 Here is the complete controller code (in Angular form): 这是完整的控制器代码(以Angular形式):

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@email.com',
                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.common['X-Requested-With'];
 })

Have a research on the concept CORS which stands for Cross-Origin Resource Sharing. 研究了代表跨域资源共享的CORS概念。 CORS is a technique by means of which resources on one location on the Internet are allowed to be requested from other domains. CORS是一种技术,通过它可以允许从其他域请求 Internet上一个位置上的资源。 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默认发送的标头,以防止此类请求:

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

Update 更新

I think, there can be only one configuration block in a module. 我认为,一个模块中只能有一个配置块。 Therefore, you need to combine 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.common['X-Requested-With'];
}])...   // rest of your code (services, factories, whatever)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM