2013-09-24 88 views
0

有没有什么方法可以配置Angular应用使其可用? 正在使用工厂。AngularJS 1.2跨域请求仅支持HTTP

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

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; 
}]); 
+0

也许如果我使用jQuery这个部分呢? – user1214120

+1

http://stackoverflow.com/questions/16661032/http-get-is-not-allowed-by-access-control-allow-origin-but-ajax-is – Jason

+0

可能重复的[AngularJS错误:跨源请求是仅支持协议方案:http,data,chrome-extension,https](http://stackoverflow.com/questions/27742070/angularjs-error-cross-origin-requests-are-only-supported-for-protocol-schemes ) – Chirag

回答

4

终于找到了解决办法。将张贴在这里,也许它可以帮助别人:

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; 
}]); 

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

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; 
    }); 
+1

这只会使您能够跨域进行GET请求。如果你想做POST,PUT或DELETE,你将需要在你的客户端和API中启用CORS。 – JoakimB