-1

I have been trying to request data from google using the distance matrix but everytime I requested it throws up "Cross-Origin Request Blocked" using AJAX API.

Whenever I make use of PostMan it returns properly.

$.ajax({
         type: "GET",
         url: "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Obalende&destinations=Ikeja&mode=driving&departure_time=now&key=AIzaSyBTo0RgT_iA87Hd76gX8zYixB3PZh3z454",
         dataType: "json",
         crossDomain: true,
         cache: false,
         success: function(data){
         console.log(data);
  }
})

This is the error returned:

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=Obalende&destinations=Ikeja&mode=driving&departure_time=now&key=AIzaSyBTo0RgT_iA87Hd76gX8zYixB3PZh3z454&_=1555970031620. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

guradio
  • 15,524
  • 4
  • 36
  • 57
Counter J
  • 173
  • 4
  • 16

1 Answers1

0

To fix this, instead of running from your local file, host a simple http server and then hit your page from there.

Use the following command in terminal whilst in the working directory, for windows see this link microsoft simple http server

http-server -p 4090 .

will allow you to enter your browser and enter the address http://localhost:4090 , the error should not happen when using this simple http server. If you are using php in your page and need to serve these pages use

php -S 127.0.0.1:4090

Alternatively, in Safari, enable the Developer menu, and inside it click the following option

enter image description here

Chizzele
  • 292
  • 2
  • 10