2017-06-04 1 views
0

私はフロントエンドとして角度2を使用し、バックエンドにはPHPを使用しています。角度2を使用してPHPで生成されたJSON応答を読む方法

PHPはjsonデータを正しく作成しますが、角度2はファイルの内容を読み取ることができません。私は以下のエラーが発生しています。

XMLHttpRequest cannot load http://localhost:81/login.json. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404. 

JSONファイルは、http://localhost:81/login.jsonにあります。私は私のPHPファイルを実行するためにXAMPPを使用しています。

私の角2のコードは以下の通りです。

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

@Component({ 
    moduleId: module.id, 
    selector: 'app-header-modal', 
    templateUrl: './header-modal.component.html', 
    styleUrls: ['./header-modal.component.css'] 
}) 


    export class HeaderModalComponent implements OnInit { 

     private data; 

     constructor(private http:Http){ 
     } 

     ngOnInit(){ 

     } 
     ngAfterViewInit() { 
      this.getData(); 
     } 
     getData(){ 
      this.http.get('http://localhost:81/login.json') 
        .subscribe(res => this.data = res.json()); 

       console.log('User Data: '+this.data); 
     } 


    } 

私のPHPコードは以下のとおりです。

<?php 
header("Access-Control-Allow-Origin: *"); 
header("Access-Control-Allow-Headers: X-Requested-With"); 

include 'connect.php'; 

$username  = str_replace(" ", "", $_POST['username']); 
$password  = str_replace(" ", "", $_POST['password']); 


    $query  = mysql_query("select username, password, id from registration where username='".$username."' and password='".$password."'"); 
    $result  = mysql_fetch_array($query); 
    if($result){ 
     $data = array(
     array('userId' => $result['id'],'userName' => $result['username']) 
    ); 

    $fp = fopen('login.json', 'w'); 
    fwrite($fp, json_encode($data)); 
    fclose($fp); 

    ?> 
     <script> 
      history.go(-1); 
     </script> 
    <?php 


} 

?> 

誰かが助けてもらえますか?

+0

[CORS with php headers](https://stackoverflow.com/questions/8719276/cors-with-php-headers) – dave

+0

の可能な複製@dave:このヘッダをPHPファイルに追加しました。しかし、角度2ではlogin.jsonファイルを読み取ることができませんでした。私は上記の私のPHPコードを追加しました。親切にチェックしてお勧めします。 –

答えて

0

これは、使用しようとしているPHPサーババックエンドでのCORSの問題です。あなた角アプリは、CORSのためにPHPサーバにリクエストを行う能力を持っていません。

phpサーバを正しく設定したら、リクエストが機能し始めます。

More information on CORS

関連する問題