shinite
shinite

Reputation: 2108

React Component unable to make request to Google API

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

Upvotes: 0

Views: 1667

Answers (2)

Fabian Schultz
Fabian Schultz

Reputation: 18556

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>

Upvotes: 0

Pranesh Ravi
Pranesh Ravi

Reputation: 19133

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.

Upvotes: 1

Related Questions