[Fixed] Get data from local php file


I am trying to get data from a php file which is inside /app folder in my project.

PHP looks like:

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

And there is app.components.ts

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

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

    private data;

        private http:Http
        ) {}


       return this.http.get('./index.php')
                data=>this.data = JSON.stringify(data),
                error =>console.log(error),

The problem is that I am getting 404 error

GET http://localhost:4200/index.php 404 (Not Found)

How can I get data from php file locally?


Since comments tend to go unnoticed, here’s an answer gathered from our discussion:

When using a relative path like: './index.php', angular looks for this file under localhost. But you mentioned that the file is located in app-folder. So instead of providing a relative path, use the complete “url”, starting from the top level, usually src.

When this is solved, there will still be an issue, you will not be returned JSON, but instead the php-script you have written. You need a server for your php-script. If you are running on Windows, Uniform Server is a viable option during development. Just remember to enable CORS in your php-scripts, like you have:

header("Access-Control-Allow-Origin: *");

and possibly you need to enable cors in your browser. Here is the extension for Chrome browser.

Leave a Reply

(*) Required, Your email will not be published