Access-Control-Allow-Origin when sending request to google api - angularjs

Im trying to send an request in my angularjs application to google API to get the attractions in a radius around an location. But I get this error message in chrome:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.
I've tried both json and jsonp but the result is the same. :S
$http.get('https://maps.googleapis.com/maps/api/place/radarsearch/json?location=51.503186,-0.126446&radius=5000&type=museum&key=<MYKEY>')
.then(function(response) {
$scope.dataResult = response.data;
});
$scope.getlocation = function() {
$scope.method = 'GET';
$http({ method: $scope.method, url: "https://maps.googleapis.com/maps/api/place/radarsearch/json?location=51.503186,-0.126446&radius=5000&type=museum&key=<MYKEY>&callback=JSON_CALLBACK" }).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
console.log(data);
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
I dont want to show result on a map, I only want it in list format.

This is CORS issue, from the client-side you can enable cors requests like this.
angular.module('yourapp').config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
The problem with your case is , https://maps.googleapis.com/maps/api/place/radarsearch/json?location=51.503186,-0.126446&radius=5000&type=museum&key=<MYKEY> does not allow your origin to have access to the response. Therefore you are not able read it.
I hope you have a valid key and also while registering you have listed your localhost in the place of domain... as google needs to know these.

Related

XMLHttpRequest cannot load .... Response for preflight has invalid HTTP status code 401

Below is my service call where I am trying to do a basic auth. I have checked multiple blogs could not find the solution for this.
Can anybody help me to solve this issue as I am getting below error:
XMLHttpRequest cannot load
Response for preflight has invalid HTTP status code 401
I could not find the basic auth in the network tab in developer options also.
function() {
"use strict";
var APIservice = function($http, $base64) {
var getDetails = function(postData) {
$http.defaults.headers.common['Access-Control-Allow-Origin'] = "*";
$http.defaults.headers.common['Access-Control-Allow-Methods'] = "GET,PUT,POST,DELETE,OPTIONS";
$http.defaults.headers.common['Access-Control-Allow-Headers'] = "Content-Type, Authorization, Content-Length, X-Requested-With";
$http.defaults.headers.common['Content-Type'] = undefined;
console.log($http.defaults.headers.common.Authorization);
//console.log($http.defaults.headers.common.Authorization);
return $http.get('http://52.74.68.202:8080/rest/v1/step/all')
.then(function(response, headers, config) {
console.log(response);
return response;
});
};
return {
getDetails: getDetails
}
}
var module = angular.module('expframework');
module.factory("APIservice", APIservice);
module.run(['$http', '$base64', function($http, $base64) {
var authdata = $base64.encode('test:test');
$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata;
}]);
module.config(['$httpProvider', '$base64', function($httpProvider, $base64) {
var authdata = $base64.encode('test:test');
$httpProvider.defaults.headers.common['Authorization'] = 'Basic ' + authdata;
}])
}();
It is working in Safari and emulators but not working in Chrome and Firefox
Please help me to fix this. Thanks in advance.
Since your server threw a 401, I guess it tried to authenticate the preflight request. From https://stackoverflow.com/a/15734032/1225328:
The W3 spec for CORS preflight requests clearly states that user credentials should be excluded.
[...]
Simply have the server (API in this example) respond to OPTIONS requests without requiring authentication.

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

XMLHttpRequest cannot load http://api.8coupons.com/v1/getsubcategory

I am trying to access the 8coupons api since i want to learn angularjs. But, whenever i try to hit the url it displays XMLHttpRequest cannot load http://api.8coupons.com/v1/getsubcategory. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
javascript:
var getjson = angular.module('dataapp',[]);
getjson.controller('controller',function($scope,$http)
{
var url = "http://api.8coupons.com/v1/getsubcategory?key=62a3ce5309039c70b7e74e759d0092282a50558b7af45ae1ca8c4bb1fa6bb4fcb16a7c896175dd5414746e2d407098dc";
$http.get(url).success(function(data,status,headers,config){
$scope.jsondata = data;
console.log(data);
}).error(function(data,status,headers,config){
});
});
You have to change your $http request as follows.
var url = "http://api.8coupons.com/v1/getsubcategory?key=62a3ce5309039c70b7e74e759d0092282a50558b7af45ae1ca8c4bb1fa6bb4fcb16a7c896175dd5414746e2d407098dc&callback=JSON_CALLBACK&time"+Math.random();
$http.jsonp(url)
.success(function(data) {
console.log("Success");
console.log(data[0].category);
}).error(function(data) {
console.log("Error");
});
Appended the additional param in the above URL which is required for JSONP call. Read the doc for more info https://docs.angularjs.org/api/ng/service/$http#jsonp
callback=JSON_CALLBACK
Demo : http://plnkr.co/edit/m9GW6y1JuiimbvKibQZ4
I just added www.corsproxy.com as a prefix to the url domain
e.g., http://www.corsproxy.com/api.8coupons.com/.....
my problem got fixed

Getting JSON data using Angular JS's $http service

I need to get JSON data from a server with URL :
http://xxxx.xxxx.xxxx.xxxx:8084/inpulse/api/user/listall
Here's my angular code:
var app = angular.module('app',[]);
app.controller('Controller', function ($scope,$http) {
$scope.email="";
$scope.password="";
$scope.sample="";
$http({
method: 'GET',
url: 'http://xxxx.xxxx.xxxx.xxxx/inpulse/api/user/listall',
})
.success(function (data, status, headers, config) {
var ret = data;
$scope.sample = JSON.stringify(ret);
})
.error(function (data, status, headers, config) {
alert(status);
// something went wrong :(
});
});
Now the same code worked when i used a JSON test URL like http://ip.jsontest.com/.
Its Definitely not a problem with the server because I tested it with a REST client and got a response. I can't figure out what I'm doing wrong.
It might be a CORS configuration issue.
If you are trying to access the server from a page that is not in the same domain/origin, you'll get an error because the server is not configured to allow CORS.
The error reported by Chrome looks like this:
XMLHttpRequest cannot load http://xxxx.xxxx.xxxx.xxxx/inpulse/api/user/listall. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
Other than that the code seems to work just as expected.

Resources