2017-04-04 74 views
0

我使用正在使用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錯誤。

回答

2

使用CORS切換谷歌瀏覽器擴展。默認情況下,Chrome在本地主機上禁用了Chrome瀏覽器

0

CORS切換Chrome擴展程序非常適合開發工作,但在移至生產環境時仍會遇到問題。

我花了最後幾天試圖找到最乾淨的解決方案,沒有太多的運氣。 Google提供了一個客戶端JavaScript庫。但要使用它,你必須對index.html中的腳本文件進行硬編碼,我完全不同意(想想:如果設備沒有互聯網連接,你將如何處理錯誤?)

我還發現谷歌已經棄用從API的第2版到第3版的JSONP,這很糟糕,因爲這將是理想的解決方法。

相反,我能找到的唯一真正的解決方案是設置一個超級簡單的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