dimanche 22 mars 2015

Angular Cross-Origin Request CORS failure, but node http.get() returns successfully


I am trying to access an API using AngularJS. I have checked the API functionality with the following node code. This rules out that the fault lies with



var http = require("http");
url = 'http://ift.tt/1DLZThx{"PER":{"$lt":1.02595675,"$gt":0.67125}}&limit=10';

var request = http.get(url, function (response) {
var buffer = ""
response.on("data", function (chunk) {
buffer += chunk;
});
response.on("end", function (err) {
console.log(buffer);
console.log("\n");
});
});


I run my angular app with node http-server, with the following arguments



"start": "http-server --cors -a localhost -p 8000 -c-1"


And my angular controller looks as follows



app.controller('Request', function($scope, $http){
// functional URL = http://ift.tt/1CBMZ2P
$scope.test = "functional";
$scope.get = function(){

$http.get('http://ift.tt/1DLZThx{"PER":{"$lt":1.02595675,"$gt":0.67125}}&limit=10',{
params: {
headers: {
//'Access-Control-Allow-Origin': '*'
'Access-Control-Request-Headers' : 'access-control-allow-origin'
}
}
})
.success(function(result) {
console.log("Success", result);
$scope.result = result;
}).error(function() {
console.log("error");
});
// the above is sending a GET request rather than an OPTIONS request
};
});


The controller can parse the w3schools URL, but it consistently returns the CORS error when passed the asterank URL. My app avails of other remedies suggested for CORS on this site (below).


Inspecting the GET requests through Firefox shows that the headers are not being added to the GET request. But beyond that I do not know how to remedy this. Help appreciated for someone learning their way through Angular.


I have tried using $http.jsonp(). The GET request executes successfully (over the network) but the angular method returns the .error() function.



var app = angular.module('sliderDemoApp', ['ngSlider', 'ngResource']);
.config(function($httpProvider) {
//Enable cross domain calls
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});




Aucun commentaire:

Enregistrer un commentaire