0

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).

10
  • Is there any specific reason why you are making an AJAX call? There is javascript implementation for the google distance matrix API. Commented Oct 18, 2016 at 20:17
  • I just wanted to use the json from Google distance matrix API. I dint know there was a service for that. Commented Oct 19, 2016 at 5:06
  • Are you able to get it now? Here is the link for the example javascript implementation google distance matrix Commented Oct 19, 2016 at 13:51
  • No, I tried adding the script in following example (developers.google.com/maps/documentation/javascript/examples/…) in my React component but the callback does not go to the initMap function...but the code works in an html file. But since i need these scripts in my JSX its not wokring file. Commented Oct 19, 2016 at 18:08
  • You can take the javascript code from that implementation and can use it in your code. There is one more solution if you are using it from node specific. node implementation link Commented Oct 19, 2016 at 18:16

2 Answers 2

1

You cannot make network call from one domain to another domain. Browser will block this due to certain security reasons.

Read about CORS

You need to setup a server to talk to the google apis and your client(browser) should talk to your server to get the google apis data. Your server will be a proxy for accessing google apis.

Sign up to request clarification or add additional context in comments.

Comments

0

The API you're trying to access just doesn't support this and even with hacks it wouldn't work reliably. Instead, use the Google Maps JavaScript API and its Distance Matrix Service. It will handle this for you and you don't have to worry about getting the server request right.

Check out this example by Google.

Here is an example that combines the use of React and Distance Matrix Service:

class Example extends React.Component {
  constructor() {
    super();
    this.state = {
      origin: '',
      destination: '',
      distance: '',
    };
  }

  componentDidMount() {
    // Some sample data plus a helper for the DistanceMatrixService.
    const origin = new google.maps.LatLng(52.516242, 13.377720);
    const destination = 'Potsdam, Germany';
    const matrix = new google.maps.DistanceMatrixService();
    
    // Get distance from Google API, if server responds, call renderDetails().
    matrix.getDistanceMatrix({
        origins: [origin],
        destinations: [destination],
        travelMode: google.maps.TravelMode.DRIVING,
      }, 
      this.renderDetails.bind(this)
    );
  }
  
  renderDetails(res, status) {
    // If the request was successfull, fill our state with the distance data.
    if (status == 'OK') {
      this.setState({
        origin: res.originAddresses[0],
        destination: res.destinationAddresses[0],
        distance: res.rows[0].elements[0].distance.text,
      });
    } else {
      console.log(status);
    }
  }

  render() {
    return(
      <div>
        <p>Origin: {this.state.origin}</p>
        <p>Destination: {this.state.destination}</p>
        <p>Distance: {this.state.distance}</p>
      </div>
    );
  }
}

ReactDOM.render(<Example/>, document.getElementById('View'));
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.min.js"></script>

<div id="View"></div>

11 Comments

So With Distance Matrix Service i dont have to make an ajax call and the Service will automatically provide the required json?
Correct, it will provide you with the data you've requested.
hey i have to write the script in react component so i am using the following code 'componentWillMount() { const script = document.createElement("script"); script.src = "maps.googleapis.com/maps/api/…"; script.async = true; document.body.appendChild(script); },'
from the google example you gave... But how do i write the other script which creates the initMap function. I tried making a react function but this gives an error... initMap not defined.
initMap() would be a callback function that is called after the request to the Google API is successful. I edited my answer to include an example. Check it out and let me know if that makes more sense - it's a little more simple than the Google one.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.