React Component无法向Google API发出请求

时间:2016-10-18 18:13:10

标签: json ajax google-maps express reactjs

我正在尝试构建一个在服务器端使用Node和Express的React App。当我向Google API发出ajax调用时,我收到了Cross-Origin Request Blocked错误。以下是我的ajax请求:

    $.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是正确的,并且在网络浏览器上正常调用时显示json。

我在快递服务器上启用了https。但这并没有帮助。 我尝试更改数据类型:' jsonp'但是它提供了parseerror (没有调用jquery)。 jsonp需要回调,但我的控件不会转到回调函数,并且它继续给出解析错误。

我已在Google API控制台中提供了所需的凭据。并尝试使用以下脚本:

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

我在所有情况下都收到以下错误:

  

阻止跨源请求:同源策略禁止读取   远程资源在   https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=ORIGIN&destinations=END&key=YOUR_KEY。   (原因:缺少CORS标题'Access-Control-Allow-Origin'。

但错误仍然存​​在。有人可以帮我删除此错误或解析错误(如果是jsonp数据类型)。

2 个答案:

答案 0 :(得分:0)

您无法从一个域到另一个域进行网络呼叫。由于某些安全原因,浏览器会阻止此操作。

了解CORS

您需要设置服务器以与google apis和您的客户端(浏览器)通信 应该与您的服务器通信以获取谷歌apis数据。您的服务器将成为访问Google API的代理。

答案 1 :(得分:0)

您尝试访问的API不支持此功能,即使使用黑客也无法可靠地运行。相反,请使用Google Maps JavaScript API及其Distance Matrix Service。它将为您处理此问题,您无需担心服务器请求是否正确。

Google查看this example

以下是结合使用React和距离矩阵服务的示例:

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>