我使用使用Angular 2的Ionic CLI创建了一个新项目。我正在尝试调用Google Place API,但我一直在收到CORS问题。我能够在Postman和Chrome中调用API并获取数据,但是当我尝试在Ionic应用程序中进行调用时,它无法正常工作。
这是我在浏览器控制台中收到的当前错误:
XMLHttpRequest cannot load https://maps.googleapis.com/maps/api/place/textsearch/json?query=steak&key=API_KEY_GOES_HERE. 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:8100' is therefore not allowed access.
在我尝试添加一些标题后,以下是我在提供程序中的代码:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import { Place } from '../models/place';
@Injectable()
export class Places {
private apiKey = "KEY_GOES_HERE";
private apiUrl = "https://maps.googleapis.com/maps/api/place";
private headers = new Headers({ 'Accept': 'application/json' })
private options = new RequestOptions({});
constructor(public http: Http) {
this.headers.append("Access-Control-Allow-Origin", "*");
this.headers.append("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
this.headers.append("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
this.options.headers = this.headers;
}
getPlaces(keyword:string): Observable<Place[]> {
return this.http.get(`${this.apiUrl}/textsearch/json?query=` + encodeURIComponent(keyword) + `&key=` + this.apiKey, this.options)
.map(res => <Place[]>res.json());
}
}
为什么我无法在离子应用程序中进行API调用?我该如何解决?
如果删除标题,我会收到通用的CORS错误。
答案 0 :(得分:2)
使用CORS切换谷歌浏览器扩展程序。默认情况下,在chrome
中对localhost禁用CORS答案 1 :(得分:0)
CORS切换Chrome扩展程序非常适合开发工作,但在迁移到生产环境时仍会遇到问题。
我花了几天的时间试图找到最干净的解决方案而没有太多运气。谷歌确实提供了一个客户端JavaScript库。但要使用它,你必须在index.html
中对脚本文件进行硬编码,我完全不同意这一点(想想:如果设备没有互联网连接怎么办,你会如何处理错误?)< / p>
我还发现,谷歌已经从API的v2转移到v3之后已经弃用了JSONP
,这很糟糕,因为这本来是理想的解决方法。
相反,我能找到的唯一真正的解决方案是设置一个超级简单的NodeJS / Express后端,该后端为CORS正确配置,并充当您的Ionic应用程序和Google API之间的代理。
这是我第一次尝试使用Node,设置它并不困难。我在这里写了一个指南:https://www.technouz.com/4674/use-google-places-api-ionic-3-simple-nodejs-backend-heroku/并在这里创建了一个示例Git repo:https://github.com/zuperm4n/super-simple-nodejs