【问题标题】:CORS issue on calling google places API in angular 6 with material使用材料在角度 6 中调用 google 地方 API 的 CORS 问题
【发布时间】:2019-03-23 11:57:44
【问题描述】:

我正在尝试使用材料在 Angular 6 中实现 google Places 模型列表,我正在调用 google Places API,但我遇到了如下所示的 CORS 问题,

无法加载https://maps.googleapis.com/maps/api/place/autocomplete/json?input=hy&language=en 对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 Origin 'localhost:4200'。

我的代码如下,

<mat-form-field>
        <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selectedUserPlace($event)">
          <mat-option *ngFor="let place of listOfPlaces" [value]="place.description">
            {{place.description}}
          </mat-option>
        </mat-autocomplete>
        <input type="text" aria-label="Number" required (input)="getUserPLaces($event.target.value)" matInput 
           [matAutocomplete]="auto">
<mat-form-field>

getUserPLaces(value: any) {
    this.searchLocationService.loadUserPlaces(value, this.latitude, this.longitude).subscribe(
      (data) => {
        this.listOfPlaces = data['predictions'];
      }
    );
  }

loadUserPlaces(key, latitude, longitude){
    return this.httpClient.get(`https://maps.googleapis.com/maps/api/place/autocomplete/json?input=${key}&language=en`);
  }

如何在这里解决 cors 问题,我知道通过禁用 chrome 安全功能和一些扩展,我们可以避免这个问题。由于我的应用程序将投入生产,我想通过代码解决这个问题。

任何解决方案将不胜感激。

【问题讨论】:

  • 关键道具应该像key=YOUR_API_KEY

标签: angular angular-material angular6 google-places-api


【解决方案1】:

是的,是CORB问题,和CORS不同,只是设置了header,会返回如下错误:

从源“http://localhost:4200”对“https://maps.googleapis.com/maps/api/geocode/json?address=407%20N.%205th%20Ave.,%20Ann%20Arbor,%20MI,%2048104&key=AIzaSyBZAcZpANtMgkAuelnkHK1WkImpBECm4WY”处的 XMLHttpRequest 的访问已被 CORS 策略阻止:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 Access-Control-Allow-Origin .

我一直在寻找一个明确的答案,我最接近的是使用像 /// &lt;reference types="@types/googlemaps" /&gt; 这样的参考标签,即使这样也不起作用,虽然它可以满足错误,但谷歌仍然未定义出于某种原因,如果您取得任何进展,请告诉我。

【讨论】:

  • 感谢@Jeremy Sistrunk 的回答。我已经通过使用代理服务器解决了我的问题。我用谷歌地方库构建了一个节点 API,从前端调用该 API 将解决这个问题。
  • 如果您想要本地方法,我一直在使用@agm-maps,它运行良好,以防您仍在寻找本地实现。它允许您调用 MapAPIWrapper,然后,您可以初始化您的谷歌服务。 我目前的方法
  • 感谢您的回答,您能否为第二种方法发布一些代码。
猜你喜欢
  • 1970-01-01
  • 2016-09-17
  • 2016-11-14
  • 1970-01-01
  • 1970-01-01
  • 2015-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多