2017-01-23 27 views
0

我正嘗試使用Angular 2的HTTP.get()方法從本地主機發出Google Maps API JavaScript請求。在我的請求中,我需要添加標題,但我試圖執行此操作,但收到此錯誤通知:Angular 2:Google Maps API請求:不存在'Access-Control-Allow-Origin'標頭

https://maps.googleapis.com/maps/api/place/textsearch/json?query=Santa+Cruz&key=MY_KEY。 對預檢請求的響應未通過訪問控制檢查:否 請求的 資源上存在「訪問控制 - 允許來源」標頭。原因'http://localhost:51268'因此不允許 訪問。

我想要做的就是輸入一個城市名稱並將響應返回給JSON對象。有人能解釋我在這裏做錯了嗎? Web檢查上市

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); 
    } 
} 

錯誤:

enter image description here

回答

0

The answer to my solution is here.我試圖使從本地主機CORS的要求,所以我在控制檯中輸入以下命令:

chrome.exe --disable-web-security 

這會在Google Chrome上禁用相同的來源策略,並允許進行API調用。除了爲了使您在100%安全的網站開發API調用的目的以外,不應該這樣做。我敢肯定,有些人會認爲永遠不要做。

+0

您可以下載[Chrome CORS擴展](https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en)並使用滑動條,可以打開/關閉'Access-Control-Allow-Origin'。你的方式:整個網絡安全是關閉的。 – xmux

1

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

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

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

相反,只有真正的解決方案,我能找到的是成立這是CORS正確配置,並作爲您的離子應用程序和谷歌API之間的代理一個超級簡單的NodeJS /快速後端。

這是我第一次嘗試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的概念相同。

相關問題