我使用正在使用Angular 2的Ionic CLI創建了一個新項目。我試圖撥打Google Place API的電話,但我不斷收到CORS問題。我可以調用API並在Postman和Chrome中獲取數據,但當我嘗試在Ionic應用程序中進行調用時,它不起作用。調用Google Places API時出現Ionic 2 CORS問題
這是我在瀏覽器控制檯我得到的電流誤差:
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錯誤。