【问题标题】:React Component unable to make request to Google APIReact 组件无法向 Google API 发出请求
【发布时间】:2017-02-28 03:20:25
【问题描述】:

我正在尝试构建一个在服务器端使用 Node 和 Express 的 React 应用程序。我在对 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)   
   });

网址正确,浏览器正常调用时显示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 数据类型)。

【问题讨论】:

  • 您进行 AJAX 调用有什么具体原因吗?谷歌距离矩阵 API 有 javascript 实现。
  • 我只是想使用来自 Google 距离矩阵 API 的 json。我不知道有这样的服务。
  • 你现在能拿到吗?这是示例 javascript 实现的链接google distance matrix
  • 不,我尝试在我的 React 组件中添加以下示例 (developers.google.com/maps/documentation/javascript/examples/…) 中的脚本,但回调不会转到 initMap 函数......但代码在 html 文件中有效。但是由于我在 JSX 中需要这些脚本,所以它不是 wokring 文件。
  • 您可以从该实现中获取 javascript 代码,并可以在您的代码中使用它。如果您从特定节点使用它,还有另一种解决方案。 node implementation link

标签: json ajax google-maps express reactjs


【解决方案1】:

您不能从一个域向另一个域进行网络调用。由于某些安全原因,浏览器会阻止此操作。

了解CORS

您需要设置一个服务器来与 google api 和您的客户端(浏览器)通信 应该与您的服务器对话以获取 google api 数据。您的服务器将成为访问 google api 的代理。

【讨论】:

    【解决方案2】:

    您尝试访问的 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>

    【讨论】:

    • 所以使用距离矩阵服务我不必进行 ajax 调用,服务会自动提供所需的 json?
    • 正确,它将为您提供您请求的数据。
    • 嘿,我必须在 react 组件中编写脚本,所以我使用以下代码 'componentWillMount() { const script = document.createElement("script"); script.src = "maps.googleapis.com/maps/api/…"; script.async = true; document.body.appendChild(脚本); },'
    • 来自您提供的谷歌示例...但是我如何编写创建 initMap 函数的其他脚本。我尝试制作一个反应函数,但这给出了一个错误...... initMap 未定义。
    • initMap() 将是一个回调函数,在对 Google API 的请求成功后调用。我编辑了我的答案以包含一个示例。检查一下,让我知道这是否更有意义 - 它比 Google 简单一点。
    猜你喜欢
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多