首页 > 解决方案 > Angular 错误中的 Google Places API:请求的资源上不存在“Access-Control-Allow-Origin”标头

问题描述

我正在尝试设置一个 Angular 应用程序,它将根据搜索查询拉餐馆并列出他们的名字,但我无法让 Google Places API 在我的 Angular 组件/服务中工作。

这是我的服务代码:

import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class RestaurantsApiService {
  API_KEY:string ="MYKEY";
  constructor(private httpClient: HttpClient) { }
  public getRestaurants(){
    return this.httpClient.get(`https://maps.googleapis.com/maps/api/place/textsearch/json?query=restaurants+in+Sydney&key=${this.API_KEY}`);
  }
}

这是我的组件中的代码:

import { Component, OnInit } from '@angular/core';
import { RestaurantsApiService } from '../restaurants-api.service';
@Component({
  selector: 'app-restaurants',
  templateUrl: './restaurants.component.html',
  styleUrls: ['./restaurants.component.css']
})
export class RestaurantsComponent implements OnInit {
  restaurantsResults;
  constructor(private restaurantsAPI: RestaurantsApiService) { }

  ngOnInit() {
    this.restaurantsAPI.getRestaurants().subscribe((data) => {
      console.log(data);
      this.restaurantsResults = data['results'];
    })
  }

}

我的组件的html:

<p>Restaurants:</p>
<div *ngFor="let restaurant of restaurantsResults">
    <h2>{{restaurant.name}}</h2>
    </div> 

这一切都非常简单,当我将该 API 链接加载到浏览器中时,我会返回 JSON 结果。但是由于某种原因,当我从我的角度应用程序中提取时,我只是在控制台中收到了这个错误:

“从源 ' http://localhost:4200 '访问 ' https://maps.googleapis.com/maps/api/place/textsearch/json?query=restaurants+in+Sydney&key=MYKEY ' 的 XMLHttpRequest已被阻止根据 CORS 策略:请求的资源上不存在“Access-Control-Allow-Origin”标头。”

为什么会这样?老实说,我正在为一个类做这件事,我们得到了一个使用不同 API 的示例,并且该示例运行良好(从 API 获取 JSON 并显示我需要的信息)所以我不明白为什么会这样一个不工作。

我一直在寻找答案,但大多数答案与角度无关,并提到使用客户端 api,但我不明白如何为我的目的执行此操作,因为该 api 是脚本,为此我需要收集数据从没有角度加载到我的浏览器中的 json 文件中。

标签: angulargoogle-places-api

解决方案


推荐阅读