Cross domain issue in Google API's using angularJs - javascript

I am using following code to get the location details from the google API.
My code :
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
$scope.$apply(function(){
$http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng='+position.coords.latitude+','+position.coords.longitude+'&sensor=true').then(function(res){
alert(res.data);
});
});
});
}
When I try this code I am getting the Cross domain Error.
My Error:
XMLHttpRequest cannot load http://maps.googleapis.com/maps/api/geocode/json?latlng=8.5663029,76.8916023&sensor=true. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
Please suggest to solve this issue

You're sending an Authorization header ... which causes a CORS preflight check, and google doesn't like the Authorization header
you need to remove this header from the API call
see if this helps
$http.get("your long url", {headers: {Authorization: undefined}})
obviously I've replaced the actual url for readability
I've also seen the following suggestion
$http( {
method: 'GET',
url: 'someurl',
headers: {
'Authorization': undefined
}
}
)
so, rather than using the $http.get "shortcut", use $http "general" request format

I had the same issue; I was using the satellizer module for authentication.
https://github.com/sahat/satellizer
As it says on the FAQ section:
"How can I avoid sending Authorization header on all HTTP requests?"
I did:
$http({
method: 'GET',
url: 'your google api URL',
skipAuthorization: true // `Authorization: Bearer <token>` will not be sent on this request.
});
And it solved my problem; maybe you are using a third party module that modifies the header.

I can't answer in the threat of the response i want, but
Maybe your are using Interceptors in your AngularJS application, so your request is modified some time later after your configure the:
{headers: { Authorization: null } }
I'm doing more research to overcome this. I'll post my finds later.
[Edit] Wed Jul 13 2016 21:38:03 GMT-0500 (CDT) [/Edit]
My solution to this, is going with straight Javascript, in that way my petition does not is intercepted by Interceptors from the $http Service and does not have the Authorization header.
So, maybe this help someone.
Cheers!

Related

How to send client side cookies (javascript) to server side (node.js) using Microsoft Bot Framework Directline API? [duplicate]

I am working on an internal web application at work. In IE10 the requests work fine, but in Chrome all the AJAX requests (which there are many) are sent using OPTIONS instead of whatever defined method I give it. Technically my requests are "cross domain." The site is served on localhost:6120 and the service I'm making AJAX requests to is on 57124. This closed jquery bug defines the issue, but not a real fix.
What can I do to use the proper http method in ajax requests?
Edit:
This is in the document load of every page:
jQuery.support.cors = true;
And every AJAX is built similarly:
var url = 'http://localhost:57124/My/Rest/Call';
$.ajax({
url: url,
dataType: "json",
data: json,
async: true,
cache: false,
timeout: 30000,
headers: { "x-li-format": "json", "X-UserName": userName },
success: function (data) {
// my success stuff
},
error: function (request, status, error) {
// my error stuff
},
type: "POST"
});
Chrome is preflighting the request to look for CORS headers. If the request is acceptable, it will then send the real request. If you're doing this cross-domain, you will simply have to deal with it or else find a way to make the request non-cross-domain. This is why the jQuery bug was closed as won't-fix. This is by design.
Unlike simple requests (discussed above), "preflighted" requests first
send an HTTP request by the OPTIONS method to the resource on the
other domain, in order to determine whether the actual request is safe
to send. Cross-site requests are preflighted like this since they may
have implications to user data. In particular, a request is
preflighted if:
It uses methods other than GET, HEAD or POST. Also, if POST is used to send request data with a Content-Type other than
application/x-www-form-urlencoded, multipart/form-data, or text/plain,
e.g. if the POST request sends an XML payload to the server using
application/xml or text/xml, then the request is preflighted.
It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)
Based on the fact that the request isn't sent on the default port 80/443 this Ajax call is automatically considered a cross-origin resource (CORS) request, which in other words means that the request automatically issues an OPTIONS request which checks for CORS headers on the server's/servlet's side.
This happens even if you set
crossOrigin: false;
or even if you ommit it.
The reason is simply that localhost != localhost:57124. Try sending it only to localhost without the port - it will fail, because the requested target won't be reachable, however notice that if the domain names are equal the request is sent without the OPTIONS request before POST.
I agree with Kevin B, the bug report says it all. It sounds like you are trying to make cross-domain ajax calls. If you're not familiar with the same origin policy you can start here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript.
If this is not intended to be a cross-domain ajax call, try making your target url relative and see if the problem goes away. If you're really desperate look into the JSONP, but beware, mayhem lurks. There really isn't much more we can do to help you.
If it is possible pass the params through regular GET/POST with a different name and let your server side code handles it.
I had a similar issue with my own proxy to bypass CORS and I got the same error of POST->OPTION in Chrome. It was the Authorization header in my case ("x-li-format" and "X-UserName" here in your case.) I ended up passing it in a dummy format (e.g. AuthorizatinJack in GET) and I changed the code for my proxy to turn that into a header when making the call to the destination. Here it is in PHP:
if (isset($_GET['AuthorizationJack'])) {
$request_headers[] = "Authorization: Basic ".$_GET['AuthorizationJack'];
}
In my case I'm calling an API hosted by AWS (API Gateway). The error happened when I tried to call the API from a domain other than the API own domain. Since I'm the API owner I enabled CORS for the test environment, as described in the Amazon Documentation.
In production this error will not happen, since the request and the api will be in the same domain.
I hope it helps!
As answered by #Dark Falcon, I simply dealt with it.
In my case, I am using node.js server, and creating a session if it does not exist. Since the OPTIONS method does not have the session details in it, it ended up creating a new session for every POST method request.
So in my app routine to create-session-if-not-exist, I just added a check to see if method is OPTIONS, and if so, just skip session creating part:
app.use(function(req, res, next) {
if (req.method !== "OPTIONS") {
if (req.session && req.session.id) {
// Session exists
next();
}else{
// Create session
next();
}
} else {
// If request method is OPTIONS, just skip this part and move to the next method.
next();
}
}
"preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Consider using axios
axios.get( url,
{ headers: {"Content-Type": "application/json"} } ).then( res => {
if(res.data.error) {
} else {
doAnything( res.data )
}
}).catch(function (error) {
doAnythingError(error)
});
I had this issue using fetch and axios worked perfectly.
I've encountered a very similar issue. I spent almost half a day to understand why everything works correctly in Firefox and fails in Chrome. In my case it was because of duplicated (or maybe mistyped) fields in my request header.
Use fetch instead of XHR,then the request will not be prelighted even it's cross-domained.
$.ajax({
url: '###',
contentType: 'text/plain; charset=utf-8',
async: false,
xhrFields: {
withCredentials: true,
crossDomain: true,
Authorization: "Bearer ...."
},
method: 'POST',
data: JSON.stringify( request ),
success: function (data) {
console.log(data);
}
});
the contentType: 'text/plain; charset=utf-8', or just contentType: 'text/plain', works for me!
regards!!

Request header values not send? CORS - jQuery Ajax

Im trying to make a request from one application to another. So i created some headers which are required by my application and filled them in for the Ajax Request. Here is my code:
$.ajax({
method: 'GET',
url: 'http://my-domain.com/apps/filters/get-filters',
beforeSend: function(request){
request.setRequestHeader("X-Webshop-Domain", window.location.host);
request.setRequestHeader("X-Language", $('html').attr('lang'));
request.setRequestHeader("X-Request-Protocol", window.location.protocol);
request.setRequestHeader("X-Api-Version", '2');
},
headers: {
"X-Webshop-Domain": window.location.host,
"X-Language": $('html').attr('lang'),
"X-Request-Protocol": window.location.protocol,
"X-Api-Version": '2',
},
data: {}, success: function ( response )
{
}
});
Now when i load a page, this method is called but no response given. It gives me the "Header not allowed" issue. But when i check in my network tab (developer tools Chrome) i see my request, i see some headers but none of those. Does anybody has a idea how this is possible or what im doing wrong?
In case of CORS (cross domain requests), only basic headers are allowed. You will need to add the headers you wish to send to the server's response header:
Access-Control-Allow-Headers: X-Webshop-Domain, ...
Here's a related question you may find useful: Ajax Request header field Key is not allowed by Access-Control-Allow-Headers

Error access-control-allow-origin on angularjs $http.post

I wrote simple code with angularjs to communicate to PHP server API that I hosted in shared server before. I used $http.get and $http.post to get data from the server but it returned error 'access-control-allow-origin' like below:
http://dpmp.arkoding.tk/index.php/api/datapost. Response to preflight request doesn't pass
access control check: No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8100' is therefore not allowed access.
The response had HTTP status code 404.
access-control-allow-origin
most of the references that I got explained that it caused by CORS enabled on server site and just simply add a line 'header('Access-Control-Allow-Origin: *');' at the top for fix it. I have done that but it just fixed '$http.get' function and I still got the same error for '$http.post'. And made me more confused because it worked if I used postman and I thought the problem was in my angular code.
I have tried add some code in my services.js shown on the snippets below:
var datac = {id: 'helo'};
var head = {'Content-Type': 'application/json'};
return $http({
url: url + '/datapost',
method: 'POST',
headers: head,
data: datac
});
and without header
var datac = {id: 'helo'};
return $http({
url: url + '/datapost',
method: 'POST',
data: datac
});
but it wouldn't work. I even have tried to move my rest API to another hosting provider and it also returned the same error when I used angular $http.post.
I'm very appreciated for your help to my problem,
and I am sorry for my untidy english by the way :).
SOLVED IT! finally... :D
based on this link, finally I fixed the problem..
Thanks...

Response for preflight is invalid in angular

I am trying to perform test using apiary api as the following:
$scope.createAsset = function () {
$http({
method: 'POST',
url: 'http://polls.apiblueprint.org/createStory',
headers: {'Access-Control-Allow-Origin': '*'}
});
}
Apiary:
FORMAT: 1A
HOST: http://polls.apiblueprint.org/
# BulBulTest
BulBulTest is a simple API for testing.
## Create story [/createStory]
### Create story [POST]
+ Response 200 (application/json)
{
"Status": "Story created sucessfully",
"published_at": "2015-08-05T08:40:51.620Z",
"publisher": "Johm Smith"
}
and I get error even after setting the allow-origin.
You have a misunderstanding of CORS: The Access-Control-Allow-Origin header comes from the server, not the client. It's the server that decides whether to allow a cross-origin call.
There's nothing you can do in your client-side code to enable a cross-origin call if the server doesn't support it.
I don't think you have to set "Access-Control-Allow-Origin", but rather you might be missing some additional parameters since it is a POST call. If you have API method details then check what are the parameters required in "#RequestParams".Hope this might help.

CORS blocks LinkedIn share API

I try to post new content using LinkedIn share API through JavaScript from AngularJS application as given below.
var xml = "<share><comment>" + content + "</comment><visibility><code>anyone</code></visibility></share>";
var req = {
method: 'POST',
url: 'https://api.linkedin.com/v1/people/~/shares?oauth2_access_token=' + account.token,
headers: {
'Content-Type': 'text/plain'
},
data: xml
};
$http(req).success(function(data) {
console.log(data);
console.log('published to linkedin');
}).error(function() {
console.log(arguments);
console.log('failed to publish to linkedin');
});
I can successfully POST this data. However the browser blocks the response from being read because the response doesn't have an 'Access-Control-Allow-Origin' header.
But, I have given the http://localhost:3000 and 'https://localhost:3000' domains in LinkedIn application settings.
And the request/response in Chrome looks like this.
Any thoughts on how to be able to read the response and not let the browser block it?
I think the problem is the missing Access-Control-Allow-Origin header in the LinkedIn API response?
Looks like LinkedIn's REST API doesn't support CORS. They suggest to use REST API from the backend and not from browser. JS-SDK must be used from the browser.
https://developer-programs.linkedin.com/forum/cors

Categories

Resources