title: Angular4 http.post To JSON Or PHP
body: <h1>What I'm Using:</h1>
  
  <p>Angular 4 QuickStart seed using Node and NPM.</p>
  
  <h1>Goal:</h1>
  
  <p>To post data to a .json file. i.e. Add a new person to an array inside people.json</p>
  
  <h1>Issue:</h1>
  
  <p>When I use the http.post method to post data to a .json file, I get a 404 error saying that the file.json is not found.</p>
  
  <p>If I use http.get, it finds and retrieves the data just fine. The URL path that I pass in is exactly the same.</p>
  
  <h1>Code:</h1>
  
  <h3>people.service.ts:</h3>
  
  <pre><code>import { Injectable } from '@angular/core';
  import { Http, Response, Headers, RequestOptions } from '@angular/http';
  
  import { Observable } from 'rxjs/Observable';
  import 'rxjs/add/operator/catch';
  import 'rxjs/add/operator/map';
  
  import { Person} from './person';
  
  @Injectable()
  export class PeopleService
  {
      private testUrl = './data/people.json';
      constructor(private http: Http) {}
      Create(param: any): Observable&lt;Person&gt; 
      {
          let headers = new Headers({ 'Content-Type': 'application/json' });
          let options = new RequestOptions({ headers: headers });
  
          return this.http.post(this.testUrl, body, options)
                          .map(this.extractData)
                          .catch(this.handleError);
      }
  
      /*
         HELPER/ERROR
      */
      private extractData(res: Response)
      {
          let body = res.json();
          return body.data || { };
      }
  
      private handleError (error: Response | any) 
      {
          let errMsg: string;
          if (error instanceof Response) 
          {
              const body = error.json() || '';
              const err = body.error || JSON.stringify(body);
              errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
          } else 
          {
              errMsg = error.message ? error.message : error.toString();
          }
          console.error(errMsg);
          return Observable.throw(errMsg);
      }
  }
  </code></pre>
  
  <h3>person-detail.component.ts</h3>
  
  <pre><code>import { Component, Input, OnInit } from '@angular/core';
  import { ActivatedRoute, Params } from '@angular/router';
  import { Location } from '@angular/common';
  
  import { Person} from './person';
  import { PeopleService } from './people.service';
  
  @Component({
      selector: 'person-detail',
      templateUrl: './person-detail.component.html',
      styleUrls: ['./person-detail.component.css']
  })
  export class PersonDetailComponent implements OnInit
  {
      @Input() person: Person;
      errorMessage: string;
  
      ngOnInit(): void{}
  
      constructor(
          private peopleService: PeopleService,
          private route: ActivatedRoute,
          private location: Location
      ){}
  
      Add()
      {
          this.peopleService.Create(this.person).subscribe(/*person
  =&gt; person = this.person, error =&gt; this.errorMessage = &lt;any&gt;error*/);
      }
  }
  </code></pre>
  
  <h1>Edit:</h1>
  
  <p>Based on the comments about needing a server-side API to Post to, I've written a tiny test.php file and I'm getting an "Unexpected token &lt; in JSON at position 0 error"</p>
  
  <p>After reading this post, <a href="https://stackoverflow.com/questions/37948990/syntaxerror-unexpected-token-in-json-at-position-0-at-object-parse-native">SyntaxError: Unexpected token &lt; in JSON at position 0 at Object.parse (native) (AngularJS)</a>, it sounds like I'm getting an html error before my json, causing the unexpected token in JSON, but I don't know what error I might be getting as my php terminal only says "PHP Notice: Array to string conversion in C:..."</p>
  
  <h3>people.service.ts (adjusted lines only)</h3>
  
  <pre><code>import { Http, Response, Headers, RequestOptions } from '@angular/http';
  
  private testUrl = 'http://localhost:8080/test.php';
  
  Create(param: any): Observable&lt;Person&gt; 
  {
      let headers = new Headers({ 'Content-Type': 'application/json' });
      let urlParams = new URLSearchParams();
      urlParams.append('method', 'add');
      let options = new RequestOptions({ headers: headers, search: urlParams 
      });
  
      return this.http.post(this.testUrl, param, options)
                      .map(this.extractData)
                      .catch(this.handleError);
  }
  </code></pre>
  
  <h3>test.php</h3>
  
  <pre><code>&lt;?php
  header("Access-Control-Allow-Origin: *");
  header("Access-Control-Allow-Headers: Content-type");
  
  $method = $_SERVER['REQUEST_METHOD'];
  //$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
  $input = json_decode(file_get_contents('php://input'),true);
  
  echo "&lt;br&gt;";
  echo "&lt;br&gt;";
  echo "Request method: ".$method;
  echo "&lt;br&gt;";
  //echo "Request: ".$request;
  echo "&lt;br&gt;";
  echo "Request input: ".$input;
  
  ?&gt;
  </code></pre>
  
  <p>PHP is running on the PHP built-in web server with this command entered from the location of test.php in the project folder:</p>
  
  <pre><code>php -S localhost:8080 test.php
  </code></pre>