我正在尝试使用 Angular 2 的 HTTP.get() 方法从本地主机发出 Google Maps API JavaScript 请求。在我的请求中,我需要添加 header ,并且我尝试执行此操作,但收到此错误通知:
https://maps.googleapis.com/maps/api/place/textsearch/json?query=Santa+Cruz&key=MY_KEY. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:51268' is therefore not allowed access.
我想要做的就是输入城市名称并让响应返回一个 JSON 对象。有人可以解释一下我在这里做错了什么吗?
import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions} from '@angular/http';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class SearchService {
dataHere: Object;
errorMessage: String;
constructor(private http: Http) { }
getPlaces(name: String): Observable<any> {
const url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=Santa+Cruz&key=MY_KEY";
let headers = new Headers({ 'Access-Control-Allow-Origin': '*','Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.get(url, options)
.map(r => this.dataHere = r.json())
.catch((error:any) => Observable.throw(error.json().error));
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
Web 检查器中列出的错误:
最佳答案
CORS 切换 Chrome 扩展非常适合开发工作,但当您转向生产时仍然会遇到问题。
过去几天我一直试图找到最干净的解决方案,但运气不佳。 Google 确实提供了客户端 JavaScript 库。但要使用它,你必须在 index.html
中硬编码一个脚本文件,我完全不同意(想想:如果设备没有互联网连接怎么办,你将如何处理错误?)
我还发现,在从 API v2 迁移到 v3 后,Google 已弃用 JSONP
,这很糟糕,因为这本来是理想的解决方法。
相反,我能找到的唯一真正的解决方案是设置一个 super 简单的 NodeJS/Express 后端,该后端针对 CORS 进行了正确配置,并充当 Ionic 应用程序和 Google API 之间的代理。
这是我第一次尝试 Node,设置起来并不太困难。我在这里写了一个指南:https://www.technouz.com/4674/use-google-places-api-ionic-3-simple-nodejs-backend-heroku/并在此处创建了一个示例 Git 存储库:https://github.com/zuperm4n/super-simple-nodejs
我在使用 Ionic 应用程序时遇到了问题,但对于 Angular 来说也是同样的概念。
关于javascript - Angular 2 : Google Maps API Request: No 'Access-Control-Allow-Origin' header is present,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41816460/