CORS issue with JavaScript accessing google places API [duplicate] - google-maps

This question already has an answer here:
XMLHttpRequest cannot load No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' Google maps
(1 answer)
Closed 4 years ago.
Tried multiple combinations with header to do a ajax jQuery call to google maps Places API to get the predictions.
I get following error:
Failed to load https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Amsterdam&types=geocode&key=AIzaSyBqYrYm377wh0pgINHBQfadjCokJkj_uVQ&_=1535634162773:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'https://stackoverflow.com' is therefore not allowed access.
while executing following code here in console (without the API Key in the URL):
jQuery.ajax({
type: 'GET',
url: "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Amsterdam&types=geocode&key={API Key Here}",
contentType: "application/json",
dataType: 'json',
"crossDomain": true,
headers: {
'Access-Control-Allow-Headers': 'Content-Type, Content-Range, Content-Disposition, Content-Description, x-requested-with, x-requested-by',
"accept": "application/json",
"Access-Control-Allow-Origin":"*"
},
success: postSuccess,
error: postError,
});
function postSuccess(result,status,xhr) {
console.log("postSuccess");
}
function postError(xhr,status,error) {
console.log("postError", xhr,status,error);
}
Would be great if someone can point me towards the resolution.
Edit: Searched for similar questions before asking one, found this but solution was not helpful.
Edit2: To be more specific, I would like to retrieve the JSON result from Places API in JavaScript: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Amsterdam&types=geocode&key={API Key Here}

To access the places API from javascript use the Google Maps Javascript API v3 places library.

Related

No 'Access-Control-Allow-Origin' header with xml (google places api)

I am trying to work with the google places api for a little project.
I want to display all shops that are near me. I tried the following AJAX request with the no 'Access-Control-Allow-Origin' header error as a result. After some research I understand why I get this error, but I can't find a solid solution (I dont wanna install a plugin because it has to work on all computers).
A lot of people say to use dataType jsonp, which I have used before, but when I use this (and change the type to json) I get "Uncaught SyntaxError: Unexpected token :" because the response I get uses : instead of = (I think).
I have been searching a lot of information and tried a lot of things, hopefully you guys can help me out.
$.ajax({
type: "GET",
url: 'https://maps.googleapis.com/maps/api/place/textsearch/xml?',
data: {
key: "MY KEY",
query: "supermarket",
location: "x,y",
radius: "5000",
opennow: "true"
}
}).done(function (data, textStatus, jqXHR) {
console.log(data)
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log("fail: " + textStatus);
});
The CORS headers are not set for Places API web service on Google backend servers. So you won't be able to call Places API web service from the client side JavaScript code due to the Same-Origin policy of the browsers.
In order to use Places on client side JavaScript you have to use a Places library of Google Maps JavaScript API. The places library has nearby and text search functionality very similar to the corresponding web service.
For further details please have a look at the documentation:
https://developers.google.com/maps/documentation/javascript/places
Hope it helps!

How to read MediaWiki API JSON response

I am trying to search images on Wikimedia Commons, using MediaWiki API. Here is my requested URL with search params:
https://commons.wikimedia.org/w/api.php?action=query&list=allimages&format=json&aifrom=Dada
I am succeed to get response in JSON format, but I could not read it programmatically because:
No 'Access-Control-Allow-Origin' header is present on the requested
resource.
Any advice?
UPDATE:
I have added one more param to the url: callback=JSON_CALLBACK, which transforms response to jsonp format. Now it possible to use angular $http.jsonp() method also.
use jsonp1 as dataType to prevent the "No 'Access-Control-Allow-Origin' header is present on the requested resource." error. Then it works :
$.ajax({
dataType: 'jsonp',
url : 'https://commons.wikimedia.org/w/api.php?action=query&list=allimages&format=json&aifrom=Dada',
success : function(json) {
json.query.allimages.forEach(function(item) {
$('<img/>', { src : item.url }).appendTo('#images');
})
}
})
Here I add each image to a #images <div> just for demonstration purposes.
demo -> http://jsfiddle.net/52g2Lazw/
1) JSONP stands for “JSON with Padding” and it is a workaround for loading data from different domains. It loads the script into the head of the DOM and thus you can access the information as if it were loaded on your own domain, thus by-passing the cross domain issue cite.
If you are accessing the Wikimedia Commons API from a Wikimedia wiki, you can use the origin parameter of the API and this way make the API setting CORS headers. E.g. on en.wikipedia.org, you could access the Commons API this way:
$.get('https://commons.wikimedia.org/w/api.php?' +
$.param({
format: 'json',
action: 'query',
list: 'allimages',
aifrom: 'Dada',
origin: location.protocol + '//' + location.host
})).done(function() { /*...*/ });
It is generally safer to use JSON (a pure data format) than loading and executing JavaScript (JSONP) file that could, in theory, do evil with your visitors. I would probably set up a proxy server for this purpose, instead of using JSONP. A simple web search for set up a proxy json may result in plenty of useful results.

integration of scala service with web app in html5

I have a Scala service and a web app in HTML5 . The web app is used to register a user to a particular group and the service is used to post the data in database. Now I want to integrate the service with the web app such that when the user fills the form and clicks the submit button the service should be called and should update the database. I am using ajax
$.ajax({
method: "POST",
crossDomain: true,
url: "http://20.201.151.134:8091/update ",
data: JSON.stringify({name:name,
shortid:shortId,
password:pass}) ,
contentType: "application/json",
dataType: "json"
}).done(function( data ) {
alert( "Data Saved: " + data );
});
and in build.sbt file I have included the dependency
"com.thetransactioncompany" % "cors-filter" % "1.3.2"
But I'm still getting the error:
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 400.
Can anyone plz help to resolve it?
Have you added a 'Access-Control-Allow-Origin' header in your service?
I think you should add this in order the cross origin security works properly: something like response.header('Access-Control-Allow-Origin: http://trusted.site')

Ajax Request gives "uncaught SyntaxError: Unexpected end of input "

I have a problem with my Ajax Request I want to send to a specific page. I know that I can't just send Ajax requests to different pages because of the cross-domain problem. So I have chosen the jsonp method to do that.
My code is:
exs = function(url){
$.ajax({
type: "GET",
dataType: 'jsonp',
jsonp: "callback",
url: "http://example/api.php?callback=?",
success: function(response) {
console.log(response);
}
});
}
So what this returns is the following:
"Uncaught SyntaxError: Unexpected end of input"
Does anyone know what's the problem?
I have checked the page of the API I'm sending the request, there I see just plain HTML.
And I want to save that HTML output to a variable.
I haven't found a solution yet. Any ideas?
I know that I can't just send Ajax requests to different pages because of the cross-domain problem. So I have chosen the jsonp method to do that.
If you want to use JSONP then the server has to provide a JSONP response, not an HTML response.
You can't bypass the same origin policy without either the cooperation of the server or the use of a proxy.
If you were using JSONP, then you should specify dataType: "jsonp" not dataType: "json" and you should generally avoid specifying the name of the function using jsonp: "callback" in favour of letting jQuery generate it from the success argument.

Sendgrid API - JSON call

I'm trying to receive data from SendGrid API
$.ajax({
type:'GET',
url:"https://sendgrid.com/api/bounces.get.json",
data: {api_user:'username',api_key:'userkey',date:1},
success: function(data){
console.log(data)
},
crossDomain: true,
dataType: 'jsonp',
error:function(a,b,c){
console.log(a);
}
});
Console shows:
Object { readyState=4, status=200, statusText="success"}
parsererror
Error: jQuery17208301184673423685_1374648217666 was not called
Where is the bug or issue ?
The issue is that SendGrid does not support jsonp.
Unfortunately, switching to plain JSON will not work either, as SendGrid has no CORS headers and browsers will not allow you to access the pages. In short you cannot make AJAX requests dorectly to SendGrid.
However, generally this is for the better as all SendGrid endpoints require authentication and having your username and password in an AJAX request would allow users to take them and then use them to send email.
To get these stats on the frontend, you'll need a server to get them and output them on your domain or a domain with CORS allowances.
Here comes a one click solution!
Deploy your instance of SendGrid Proxy to Heroku
Use {your-sendgrid-proxy}.herokuapp.com instead of api.sendgrid.com
Done (Really)
How it works:
It creates a node powered http proxy using express-http-proxy
It adds needed headers such as Authorization and Content-Type
It overrides Access-Control-Allow-Origin to * to make your browser CORS warning free
See how the magic is working. Feedback is welcome!