I am trying to build a React App that uses Node and Express on the Server side. I am getting Cross-Origin Request Blocked error when i am making an ajax call to Google API.Following is my ajax request:
$.ajax({
url:
'https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins='+start+'&destinations='+end+'&key=%20'+Key,
dataType: 'json',
cache: false,
crossDomain: true,
success: function(data) {
console.log(json);
}.bind(this),
error: function(xhr, status, err) {
console.error('https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins='+start+'&destinations='+end+'&key=%20'+Key, status, err.toString());
}.bind(this)
});
Url is correct and displays json when normally called on web browser.
I have enabled https in my express server.But that doesn't help. I tried changing datatype : 'jsonp' but it gives parseerror (jquery was not called). jsonp requires a callback but my control is not going to the callback function and it continues giving parse error.
I have made the required credentials in Google API console.And tried using the following script:
<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>
<script>
function start() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: 'CLIENT_ID.apps.googleusercontent.com',
});
});
}
</script>
I'm getting the following error in all cases:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=ORIGIN&destinations=END&key=YOUR_KEY. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
But the errors remain. Can someone please help me remove this error or the parse error(in case of jsonp datatype).