如何使用 angular 读取 PHP 产生的 JSON 响应 2

How to read JSON response produced by PHP using angular 2

我使用 angular 2 作为前端,PHP、MySQL 作为后端。

PHP 正确创建 json 数据但 angular 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 位置。我正在使用 XAMPP 到 运行 我的 php 文件。

我的 angular 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


}

?>

谁能帮忙!

这似乎是您尝试使用的 php 服务器后端的 CORS 问题。由于 CORS,您 angular 应用无法向 php 服务器发出请求。

正确配置 php 服务器后,请求应该开始工作。

More information on CORS.