【问题标题】:Google Places API: No 'Access-Control-Allow-Origin' header is present on the requested resource [duplicate]Google Places API:请求的资源上没有“Access-Control-Allow-Origin”标头[重复]
【发布时间】:2018-12-29 15:24:36
【问题描述】:

我正在尝试从 Angular 应用程序拨打电话,但我收到以下错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

这是我的代码:

constructor(private http: Http) { 
  }

getNearbyRestaurants(lat: number, lng: number){
    return this.http.get(this.API_URL+this.API_KEY+`&location=${lat},${lng}`).pipe(
      map(result => result)
        );
      }
    }

有人知道如何解决这个问题吗?谢谢

【问题讨论】:

    标签: rest api google-maps google-maps-api-3 google-places-api


    【解决方案1】:

    您尝试通过 AJAX 请求使用 Places API Web 服务调用。在这种情况下,您将面临Same Origin policy。不幸的是,Google 服务器没有在响应中设置 CORS 标头,您的浏览器会阻止此请求。

    Google 假设 Places API 网络服务请求在服务器端执行,但您尝试在客户端执行。对于客户端,Google 在 Maps JavaScript API 中有一个 places library,它提供了类似于网络服务的功能。

    为了解决您的问题,您应该使用 Maps JavaScript API 的地点库或创建中间服务器,向 Google 发送请求并将结果传回您的 Angular 应用程序。

    您可以在https://developers.google.com/maps/documentation/javascript/examples/place-search查看使用 Maps JavaScript API 的地点库编写的附近搜索示例

    我希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2021-09-25
      • 2015-06-15
      • 2017-02-07
      • 2023-03-16
      • 2014-07-30
      • 2016-01-14
      • 2023-03-15
      • 2018-12-02
      • 2019-01-13
      相关资源
      最近更新 更多