2017-08-30 30 views
0

當我嘗試從鏈接(php服務器)檢索對象列表時出現錯誤。多來源請求的錯誤HTTP GET對象列表

阻斷(跨來源請求):「相同 源」策略不允許訪問位於 HTTP遠程資源://localhost/eReport/index.php。原因: CORS中缺少「訪問控制授權源」令牌 「Access-Control-Allow-Headers」CORS頭。

我在這個鏈接上添加了一個像這個tuto這樣的標題,但我仍然有這個錯誤。

你能幫助我嗎?

我的服務頁面:

@Injectable() 
export class ReportService{ 
    private baseUrl: string = 'http://localhost/report/reports.php'; 

    constructor(private http : Http){} 
    getAll(): Observable<Report[]>{ 
    let report$ = this.http 
     .get(`${this.baseUrl}`, { headers: this.getHeaders()}) 
     .map(mapReports); 
     return report$; 
    } 

    private getHeaders(){ 
    // I included these headers because otherwise FireFox 
    // will request text/html 
    let headers = new Headers(); 
    headers.append('Accept', 'application/json'); 
    headers.append('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); 
    return headers; 
    } 
    get(id: number): Observable<Report> { 
    let report$ = this.http 
     .get(`${this.baseUrl}/report/${id}`, {headers: this.getHeaders()}) 
     .map(mapReport); 
     return report$; 
    } 

我的PHP頁面

header("Access-Control-Allow-Origin: *"); 
     $tab = array(
     array('id'=> '12', 'name'=> 'test','description' => '2018-04-01','url'=>'../../../assets/img/chat1.png'), 
     array('id'=> '13', 'name'=> 'test','description' => '2018-04-01','url'=>'../../../assets/img/highcharts.png') 
    ); 

    echo json_encode($tab); 


?> 
+1

你得到什麼樣的錯誤? – ivanasetiawan

+0

阻止多源請求(跨源請求):「相同源」策略不允許訪問位於http://localhost/eReport/index.php的遠程資源。原因:CORS「Access-Control-Allow-Headers」CORS頭中缺少「Access-control-authorization-origin」令牌。 – Yago

+0

這是來自你的服務器端,你需要在那裏允許跨不同域的請求 –

回答

0

也許是最快的解決方法是改變自己的基本網址在角應用/report/reports.php如果請求會到爲該應用提供服務的同一臺服務器。

由於客戶端發送類型爲application/json的內容,瀏覽器不會立即發送請求,因此您的請求不起作用。如果您重新啓動瀏覽器,然後觀察網絡選項卡,你會發現,而不是你的GET,一個OPTIONS請求先發,包括類似於這些標題:

Origin: yourserver 
Access-Control-Request-Method: GET 
Access-Control-Request-Headers: Content-Type, Accept 

在這種情況下,瀏覽器預計服務器返回不僅僅是Access-Control-Allow-Origin頭(這你已經做),但所有這些:

Access-Control-Allow-Origin: yourserver (or *) 
Access-Control-Allow-Methods: GET (or a list eg: GET, POST, OPTIONS) 
Access-Control-Allow-Headers: Content-Type, Accept (the same headers from above) 

所以,你需要閱讀來自先前塊的請求頭,並設置響應報頭使用時,它們的值。如果你有apache_request_headers()方法,那很簡單。您也可以從超全球的$_SERVER獲得它們。

// set required headers: 
header("Access-Control-Allow-Origin: $_SERVER[HTTP_ORIGIN]"); 
header("Access-Control-Allow-Methods: $_SERVER[HTTP_ACCESS_CONTROL_REQUEST_METHOD]"); 
header("Access-Control-Allow-Headers: $_SERVER[HTTP_ACCESS_CONTROL_REQUEST_HEADERS]"); 

See this helpful article