0

I've been trying to figure this out for almost a day, with no luck. I have a simple http.post request:

  import { Component } from '@angular/core';
  import { Http, Response, Headers, RequestOptions } from '@angular/http';
  import 'rxjs/add/operator/toPromise';

  @Component({
    selector: 'SendPost',
  })
  export class SendPostComponent {

    constructor(
        private http:Http,
    ) {}

    private urlPost:string = 'www.mydomain.com/api/order.php'

    private addToBasket() {
      var data = {
        foo: "bar",
        foo1: "another"
      }
        var postData = JSON.stringify(data);

        let headers = new Headers({'Content-Type': 'application/json'}); //x-www-form-urlencoded
        headers.append('Access-Control-Allow-Methods', "GET, POST, OPTIONS");
      let options = new RequestOptions({ headers: headers });

      this.http.post(
            this.urlPost, 
            postData, 
            options
        )
        .toPromise()
                .then((res) => {this.extractData(res)});
    }       

    private extractData(res: Response) {
        console.log('extractData:', res);
    }

  }

I striped the API endpoint to absolute minimum: no .htacces, just the php file this simple code:

<?php print_r(json_encode($_REQUEST)); die; ?>

I keep getting an empty array in return. However, if I change the code like this:

var data2 = 'foo=bar&foo1=another'
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });

Then the $_REQUEST objects gets my data. What am I missing?

Vali Munteanu
  • 469
  • 3
  • 15
  • If you get the results with URL parameters, then it's php related, not angular related ! I'm not familiar with PHP, but maybe you should set it to accept JSON post requests –  Sep 01 '17 at 13:26
  • `JSON.stringify` will return a json string but what you need is https://stackoverflow.com/questions/1714786/query-string-encoding-of-a-javascript-object – ka_lin Sep 01 '17 at 13:30

1 Answers1

1

PHP $_REQUEST is:

An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE

and $_POST

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

PHP can't parse "application/json" data, the workaround is php wrapper, by using "file_get_contents('php://input')" you can fetch the data from request entity body in this way:

$body = file_get_contents('php://input');
$data = json_decode($body);
print_r($data);  // here is what you need
kite.js.org
  • 1,599
  • 10
  • 11