CORS angularjs $http.get - angularjs

I'm trying to consume a josn api (I'm very new to angularjs) and I'm getting the following error when trying to consume a json api using $http.get
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401.
angularjs version: 1.3.8
browser: chrome/firefox/safari
enable CORS on the server side is not an option
already tried jsonp without success
the url works when I use the browser (I see the json response)
My Code:
angular.module('MyApp', [])
.config(function ($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
})
.controller('MainController', function($scope, $http) {
var url = "https://myurl";
$http.get(url)
.success(function(data){
console.log(data);
});
});
Thanks in advance!

Related

Getting error when trying get JSON from remote url

I'm trying load this json file from remote url. In the beginning I was using $http.get function, but I was getting the next error message:
CORS 'Access-Control-Allow-Origin'
Now I am using JSONP, but nothing happens.
service.js file:
angular.module("elcomaApp").factory('ElcomaService', ['$http', function($http){
return $http({
method: 'JSONP',
url: 'http://vagalumewifi.com.br/timeline.json'
}).success(function(response){
return response.data;
}).error(function(err){
return err;
});
}]);
controller.js file:
angular.module("elcomaApp", []).controller('MainController', ['$scope', 'ElcomaService', function($scope, ElcomaService){
$scope.name = 'Natanael Santos';
console.log($scope.name);
ElcomaService.success(function(data){
$scope.elcomaData = JSON.parse(data);
var i = 0;
for (x in $scope.elcomaData){
console.log(i);
i++;
console.log(x.date);
}
}).error(function(data){
console.log(data);
});
}]);
app.js file:
var app = angular.module("elcomaApp", ['ngMaterial', 'ngRoute']);
I already hava read a lot of articles on stackoverflow, but no one work for me.
I'd suggest using $http.jsonp(url) method:
angular.module("elcomaApp").factory('ElcomaService', ['$http', function($http) {
$http.jsonp('http://vagalumewifi.com.br/timeline.json')
.success(function(data) {
console.log(data); // you can't `return` here...
}).error(function(err){
console.err(err);
});
}]);
Note: be warned that you can't expect that return in an async method has the same behavior as in a sync environment... :-)
Your original error is your clue. The endpoint server won't allow access from another domain.
CORS: Cross Origin Requests
You need to allow access on the endpoint server for the type of HTTP method you want to use (i.e. GET, POST, HEAD, ...) Additionally depending on what you're doing you may need to allow for an OPTIONS request, see Preflighted Requests in the MDN documentation above.
If you don't have access to that server you may need to do a work around by making $http call a script on your server that will fetch the file for you. I've done this before using PHP as a proxy and using PHP's file_get_contents function to grab files from other servers of a different domain.

How do you pass in HTTP headers to make a request from an API?

Using Angular, I'm trying to pass in HTTP headers with the request, “App-Id” and “App-Key” to get data from this API.
I tried setting the headers like this:
$http.defaults.headers.common["App-Id"] = '5a3d8b8d';
$http.defaults.headers.common["App-Key"] = '738e9aca62e7465446b7be8fe4219ffa';
but I got a Response for preflight is invalid error.
http://jsfiddle.net/9Ymvt/4573/
Adding Headers to an $http Request on a Per Request Basis
To add headers to a $http request on a per request basis, add them to the headers property of the $http config object.
var xheaders = {};
xheaders["App-Id"] = '5a3d8b8d';
xheaders["App-Key"] = '738e9aca62e7465446b7be8fe4219ffa';
var xurl = 'https://uk.bookingbug.com/api/v1';
var configObj = { method: 'GET',
url: xurl,
headers: xheaders
};
$http(configObj)
.then(function onFulfilled(response) {
console.log(response);
vm.headers = response.config.headers;
vm.data = response.data
}).catch( function onRejection(errorResponse) {
console.log("Error: ", errorResponse.status);
console.log(errorResponse);
vm.error = errorResponse;
})
;
The code was getting pre-flight errors because it was using the incorrect URL. The correct base URL is https://uk.bookingbug.com/api/v1 which supports App-Id headers and CORS.
The DEMO on JSFiddle.
I do not think this is a complete answer to your question, but here is what I have in my project:
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
// code for routes
});
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
This solves my problem with CORS. If you want to do another type of header, you probably can find your answer here.
Preflight errors are related to CORS. You might want to look at rack-cors to enable cross-site api calls via javascript. There is a manual configuration here: https://gist.github.com/dhoelzgen/cd7126b8652229d32eb4

Response Object coming null for get request for rest api

I am trying to implement nexmoverify REST API for OTP implementation but response object comig null.I checked in Postman and able to get stringify object from of response object.
var app = angular.module('angularjs-starter', []);
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
app.controller('MainCtrl', function($scope, $http) {
$scope.addNewChoice = function () {
console.log('aaaa');
$scope.res=$http.get("https://api.nexmo.com/verify/json?api_key=56a9b1af&api_secret=XXXXXX&number=919650298011&brand=stayuncle").
success(function (response) {
$scope.res = response.data;
}).
error(function (response){
console.log(response);
$scope.res = response.data;
});
};
Code Flow: code flow coming to error() section and then printing null in web console.
Error :
Response object coming null as well as getting this error in web console
XMLHttpRequest cannot load https://api.nexmo.com/verify/json?api_key=56X9b1af&api_secret=d3XXXX&number=91XX50298011&brand=stayuncle. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
Can someone help me to solve this problem.
The error tells you the problem.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8080' is therefore not allowed
access.
The REST API server is not configured for CORS, therefore, you are not allowed to access that URL from any origin other than the https://api.nexmo.com/ domain. However, aren't you supposed to be using JSONP?
Reference on CORS
Reference on JSONP

Angular $http request issue

i am trying to retreive some images from a flickr service this one.
Unfortunately, i have the following error:
XMLHttpRequest cannot load http://api.flickr.com/services/feeds/photos_public.gne?format=json.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed access.
Here's my code:
angular.module('myApp')
.service('getFlickrImages', function($http){
this.getData = function() {
delete $http.defaults.headers.common['X-Requested-With'];
return $http({
method: 'GET',
url: 'http://api.flickr.com/services/feeds/photos_public.gne?format=json'
});
}
});
angular.module('myApp')
.controller('MainCtrl', function ($scope, getFlickrImages) {
$scope.data = null;
getFlickrImages.getData().then(function(dataResponse) {
$scope.data = dataResponse;
});
});
Here's a Plunker if someone can help me
I finally found that chrome plugin:
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=chrome-ntp-icon
Install it, activate it and refresh the view.
It will a least let you work without that Access-Control-Allow-Origin issue.
It would be good if someone bring the fix but directly in the code...

Access Control Allow Origin | AngularJS

I was integrating the flickr app into my app.
I am receiving the error below:
XMLHttpRequest cannot load https://api/flickr.com/services/rest?api_key=4cd95b5ad05844319ee958bf96ec0150&format=json&method=flickr.photos.search&nojsoncallback=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://sinch12j12.ads.autodesk.com' is therefore not allowed access. The response had HTTP status code 400.
Below is the client side code:
(function() {
'use strict';
angular.module('flickrApp', ['ngMaterial'])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}])
.controller('ListController', ['$scope', '$http', function($scope, $http) {
$scope.results = [];
$scope.search = function() {
$http({
method: 'GET',
url: 'https://api/flickr.com/services/rest',
params: {
method: 'flickr.photos.search',
api_key: '4cd95b5ad05844319ee958bf96ec0150',
text: $scope.searchTerm,
format: 'json',
nojsoncallback: 1
}
}).success(function(data) {
$scope.results = data;
}).error(function(error) {
console.log(error);
});
}
}]);
})();
Please let me know how shall it may be resolved ?
You are trying to make AJAX requests to a different server (domain), that does not allow ajax requests from other domains. There are 2 solutions to your problem :
Edit the configurations of the remote server (Allow-Origin header) to allow AJAX requests from other servers. I think this solutions is not feasible in your case, as you are not capable of configuring the flickr server
Create a proxy server component in your server, exposing an API to your application. Thus, you will make the AJAX requests to your API (and since it is the same domain, you will not have a cross-domain request issue), and your server will make the requests to the flickr API and respond in your AJAX call.
You're trying to use AJAX to retrieve some data from a remote server (in this case, the Flickr server). For security reasons, AJAX calls to any file on a remote server is not permitted unless that file has allowed AJAX calls from remote servers. Here, the Flickr file your trying to get doesn't allow AJAX calls from any other servers, that's why you won't be able to access the data in that file.
Thanks and let me know if you have any more problems.

Resources