问题
I am trying to use $http service of angularJS but it doesn't seem to work. I have read up online about such an issue but the solutions given doesn't help. I have the following in my controller:
app.controller('Ctrl', function($scope, $http){
var url = http://someurl?name=foo;
$scope.submitRules = function(){
$http({method: 'GET', url: url}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
});
I am using this version of angularJS <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.4/angular.min.js"></script>
Whenever I try sending the request it shows that the request status is cancelled. The URL that I am sending the request to is very well working it just doesn't work form angularJS. Can someone help?
回答1:
I find all this CORS stuff confusing. But what can I say? I'm a slow learner. The problem you describe may be fixable from the controller, but I think it's better to set things up right at the point of entry. For example:
angular.module('myApp', ['ngResource', 'ui.bootstrap']).
config(function($httpProvider) {
// Enable CORS
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
...
});
Given the code you've provided, this may also work (not tested):
app.controller('Ctrl', function($scope, $http, $httpProvider){
var url = http://someurl?name=foo;
$scope.submitRules = function(){
// Enable CORS
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$http({method: 'GET', url: url}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
});
Either way, all the magic happens in these two line:
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
回答2:
If it's not CORS, which you can check using chromium with CORS extension, try to set timeout of your request:
app.controller('Ctrl', function($scope, $http){
var url = http://someurl?name=foo;
$scope.submitRules = function(){
$http({
method: 'GET',
url: url,
timeout: 50000
}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
});
Setting $httpProvider never worked for me, it's rather server matter.
来源:https://stackoverflow.com/questions/16085700/angularjs-http-get-is-getting-cancelled