0

I am using angular 2 as front end and PHP, MySQL for my back end.

PHP properly creates json data but angular 2 unable to read the file content. I am getting the below error.

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 file available at http://localhost:81/login.json location. I am using XAMPP to run my php file.

My angular 2 code is below.

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);
        }


    }

My PHP code is below.

<?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


}

?>

Can somebody help!

Green Computers
  • 723
  • 4
  • 14
  • 24
  • Possible duplicate of [CORS with php headers](https://stackoverflow.com/questions/8719276/cors-with-php-headers) – dave Jun 04 '17 at 07:50
  • @dave: I have added this header in my PHP file. But still angular 2 could not read login.json file. I have added my php code above. Kindly check and suggest. – Green Computers Jun 04 '17 at 07:56

1 Answers1

0

This appears to be a CORS issue with the php server backend you are trying to use. You angular App doesn't have the ability to make a request to the php server because of CORS.

Once you have properly configured the php server the request should start working.

More information on CORS.

jLee
  • 473
  • 2
  • 5