2013-09-24 87 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