angular - 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 文件中。
解决方案
推荐阅读
- asp.net - 如何使用嵌套中继器在 asp.net webform 中显示带有复选框的母公司和子公司列表以进行选择
- r - 在 R 中将多列转换为数字并将星号转换为 NA
- python - 一次在 2 个不同文件上运行程序的最佳方法
- hive - Hive 连接优化和资源分配
- dart - Flutter Drawer 作为单独的小部件不允许修改宽度
- excel - 将代码添加到现有模块:删除第 2 行中的重复值
- kubernetes - Kubernetes模式金丝雀部署冒烟测试最佳实践?
- ruby-on-rails - 存储图像以测试上传和删除的好方法是什么?
- algorithm - 在集合列表中找到相似集合的有效方法
- kotlin - 提供具有 Dagger 多绑定依赖项的实例时出错