2017-04-12 64 views
0

當我在我的Cloudant/NoSQL數據庫中使用HTTP GET時,我目前收到Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.錯誤。爲GET請求設置標頭 - Angular 2 Observable/Promise

我知道,設置Access-Control-Allow-Origin: *將允許來自localhost的GET請求,但是我沒有看到專門用於設置標題的Angular 2的文檔。

async getData(): Promise<IPost[]> { 
    return this._http.get(this._postUrl) 
     .toPromise() 
     .then(this.extractData) 
     .catch(this.handleError); 
} 

IPost[]是執行extractData()之後將要返回的對象。

任何幫助表示讚賞,謝謝你的時間!

+2

您需要在服務器上設置此標題,而不是在Angular應用程序中。 – cgatian

+0

找到它,隱藏在數據庫的設置中。謝謝! – Nihir

回答

0

我通常在調用REST API時使用它。數據是您發送的請求對象。

const HEADERS = new Headers({'Content-Type': 'application/json'}); 

    this.http.post(ENDPOINT, JSON.stringify(data), {headers: HEADERS}) 
      .map(this.extractData) 
      .subscribe(
      payload => { 
          //do some operation or set values with payload 
         } 
     ); 

這是後調用。如果您想使用GET調用,則不必在角度2側設置任何標題。只有在後端才需要允許本地主機/特定機器的請求。