2017-06-19 59 views
-1

我打電話給一個簡單的get請求通過localhost.I不知道什麼錯誤的代碼。我檢查了很多time.It沒有發現任何錯誤。有人檢查我的代碼告訴我什麼我錯過了。基本的角度2認證

import { Injectable } from '@angular/core'; 
import { Http, Response,Headers,RequestOptions } from '@angular/http'; 

import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/operator/do'; 
import 'rxjs/add/operator/catch'; 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/observable/throw'; 

import { IProduct } from './product'; 

@Injectable() 
export class ProductService { 
    //private _productUrl = 'api/products/products.json'; 
    //private _productUrl = 'http://localhost:8092/openmrs-standalone/ws/rest/v1/concept'; 
    private _productUrl = 'http://localhost:8092/openmrs-standalone/ws/rest/v1/session'; 

    constructor(private _http: Http) { } 

    getProducts(): Observable<any> { 

     let username: string = 'admin'; 
     let password: string = 'Admin123'; 
     let headers: Headers = new Headers(); 
     headers.append("authorization", "Basic " + btoa(username + ":" + password)); 
     headers.append("Content-Type", "application/json"); 
     let options = new RequestOptions({ headers: headers, withCredentials: true }); 

     return this._http.get(this._productUrl,options) 

      .map((response: Response) => <IProduct[]> response.json()) 
      .do(data => console.log('All: ' + JSON.stringify(data))) 
      .catch(this.handleError); 

    } 
    private handleError(error: Response) { 
     // in a real world app, we may send the server to some remote logging infrastructure 
     // instead of just logging it to the console 
     console.error(error); 
     return Observable.throw(error.json().error || 'Server error'); 
    } 
} 
+0

嘗試爲什麼功能的getProducts()調用驗證API? –

+0

我只是爲了測試目的。我想調用其餘的API來獲取數據.Newbie to angular 2 –

+0

我現在發佈了完整的代碼。 –

回答

0

你可以用這個

private _productUrl = 'http://localhost:8092/openmrs-standalone/ws/rest/v1/session'; 

getProducts(): Observable<any> { 
    let username: string = 'admin'; 
    let password: string = 'Admin123'; 
    let headerOptions = { 
     'Accept': `application/json`, 
     'Access-Control-Allow-Credentials': 'true', 
     'Authorization': 'Basic ' + btoa(username + ":" + password) 
    }; 
    let headers = new Headers(headerOptions); 
    return new RequestOptions({ headers: headers }); 
} 
+0

謝謝,但我得到同樣的錯誤。 –

+0

阻止跨源請求:相同的源策略不允許讀取http:// localhost:8092/openmrs-standalone/ws/rest/v1/session中的遠程資源。 (原因:缺少CORS頭'Access-Control-Allow-Origin')。 –

+0

我認爲這個錯誤來自服務器,你應該添加配置標題設置訪問控制允許來源「*」,以允許CORS –