2017-02-04 53 views
1

通過GET請求this quick exampleAngular2運行到PHP文件後,我繼續得到 -一個GET請求跨域和港口Angular2到PHP

錯誤304

我測試的區別使用nodephp作爲angular2app的後端。我有一個簡單的GET請求,它試圖從php文件中檢索少量數據。

請求似乎很好,但文件沒有提供給應用程序。

304不修改有條件GET或HEAD請求已收到 並會導致在一個200 OK響應,如果它不是爲了 事實的條件評價爲假。

換句話說,

沒有必要爲服務器,因爲該請求指示該客戶端,這使得該請求的條件,已具有有效的表示轉移目標資源的表示;服務器因此重定向客戶端以使用該存儲的表示,就好像它是200 OK響應的有效載荷一樣。

CORS

CORS允許express app.js文件中。

我在PHP文件中允許有CORS

我該如何解決這個問題?我會至少喜歡從ng2一側的console.log數據。

代碼示例

PHP //運行Apache的端口上80 @ api.example.com

<?php 
    header("Access-Control-Allow-Origin: *"); 
    $data = array(
     array('id' => '1','first_name' => 'Cynthia'), 
     array('id' => '2','first_name' => 'Keith'), 
     array('id' => '3','first_name' => 'Robert'), 
     array('id' => '4','first_name' => 'Theresa'), 
     array('id' => '5','first_name' => 'Margaret') 
    ); 

    echo json_encode($data); 
?> 

Angular2 //運行在Express服務器@本地:4200

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

@Component({ 
    selector: 'my-app', 
    template: `<ul> 
     <li *ngFor="let person of data"> 
      {{person.id}} - {{person.first_name}} 
     </li> 
     </ul>` 
}) 
export class AppComponent { 

    private data; 

    constructor(private http:Http){ 
    } 

    ngOnInit(){ 
     this.getData(); 
    } 

    getData(){ 
     this.http.get('api.example.com/index.php') 
       .subscribe(res => this.data = res.json()); 
    } 
} 

我試圖修改getData()功能沒有工作。最近這個,

getData(){ 
    let url = 'api.example.com/index.php'; 
    let headers = new Headers({ 'Content-Type': 'application/json' }); 
    let options = new RequestOptions({ headers: headers }); 
    this.http.get(url, options) 
     .subscribe(res => { 
      this.data = res.json(); 
     console.log(this.data); 
     }); 
    } 
+0

也許這將幫助http://stackoverflow.com/questions/26166433/how- to-prevent-request-that-returns-304/26339940#26339940 –

+1

@suraj謝謝。嘆。這浪費了很多時間。多麼痛苦的人。我以前從未收到錯誤304。謝謝! – wuno

回答

1

我有類似的問題,但已能夠解決它通過在我的api腳本上設置以下標頭;

if (isset($_SERVER['HTTP_ORIGIN'])) { 

header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); 
header('Access-Control-Allow-Credentials: true'); 
header('Access-Control-Max-Age: 86400'); // cache for 1 day} 

//由於OPTIONS期間接收訪問控制頭請求

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { 

if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) 
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");   

if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) 
    header("Access-Control-Allow-Headers:  {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); 
exit(0); } 

希望它可以幫助

+1

lyke我很欣賞你的意見。我解決了問題,但希望這可以幫助別人。 – wuno