javascript AngularJS 1.2 跨域请求仅支持 HTTP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18990141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:59:00  来源:igfitidea点击:

AngularJS 1.2 cross origin requests are only supported for HTTP

javascripthtmlangularjs

提问by user1214120

Is there any way to configure Angular app to make it available? Im using a factory.

有没有办法配置 Angular 应用程序以使其可用?我正在使用工厂。

By the way, I'm using localhost as webserver but I'm making a request to other server (same network).

顺便说一句,我使用 localhost 作为网络服务器,但我正在向其他服务器(同一网络)发出请求。

angular.module('demoApp.factories', [])
    .factory('dataFactory', ['$http', function($http) {

    var urlBase = 'external-server:8080';
    var dataFactory = {};
    dataFactory.getTest = function () {
        return $http.get(urlBase + '/test');
    };

    return dataFactory;
}]);

回答by user1214120

Finally found the solution. Will post here, maybe it can help others:

终于找到了解决办法。将在这里发布,也许它可以帮助其他人:

angular.module('demoApp.factories', [])
    .factory('dataFactory', ['$http', function($http) {

    var urlBase = 'external-server:8080';
    var dataFactory = {};
    dataFactory.getTest = function () {
        //Note the $http method changed and a new parameter is added (callback)
        //the value of the callback parameter can be anything
        return $http.jsonp(urlBase + '/test?callback=myCallback');
    };

    return dataFactory;
}]);

The controller file basically just calling this factory:

控制器文件基本上只是调用这个工厂:

angular.module('demoApp.controllers', []).controller('controller1', ['$scope', 'dataFactory', 
        function ($scope, dataFactory) {

    $scope.status;
    $scope.data;
    dataFactory.getTest().success(function (data) 
    {
        $scope.data = data;
    }).error(function (error) 
    {
        $scope.status = 'Unable to load customer data: ' + error.message;
    });

回答by Michael Tang

You may be looking to configure the $httpProvider as specified here: http://better-inter.net/enabling-cors-in-angular-js/

您可能希望按照此处指定的方式配置 $httpProvider:http://better-inter.net/enabling-cors-in-angular-js/

Another way is to create a simple http proxy on your front-end server to make external requests look like to angular that they're coming from the same server.

另一种方法是在您的前端服务器上创建一个简单的 http 代理,以使外部请求看起来像是来自同一服务器的角度。