Angular2 Http protocol might not be posting properly

147 views Asked by At

So here's my http code:

    let headers = new Headers ({ 'Content-Type': 'application/json' }); 
    let options = new RequestOptions({ headers: headers }); 
    if (body == null)
    {   
        body = {title: "hi", search: "person"};
    }   
    console.log('body: ' + JSON.stringify(body));

    return this.http.post('app/php/check.php', body, options)
        .toPromise()
        .then(response => response.text())
        .catch(this.handleError);

I'm unsure if the server is receiving the data correctly but I am sure that it's posting something as I can see:

[
  {
    "select": "title",
    "search": "person"
  }
]

with firebug.


In my php file all I'm doing is print_r($_REQUEST), however all it returns is an empty array.

Is there anything I'm doing wrong?

Bonus question: Are there any other data extraction functions apart from .json() and .text() for responses?



Update:

Interestingly, if I use the url app/php/check.php?fruit=apple there is a response. Anyone know the discrepancy?

1

There are 1 answers

10
J J B On BEST ANSWER

The server should be receiving the data that's in your body variable.

Here is an example of how you should be retrieving the output from your function. The example is using a JSON output though due to the test API I'm using for the post data. A string will be the same just change the return section.

ngOnInit() {
      this.postRquest().then(results => this.response = results);
}

postRquest(body) {
    let headers = new Headers ({ 'Content-Type': 'application/x-www-form-urlencoded' }); 
    let options = new RequestOptions({ headers: headers }); 
    if (body == null)
    {   
        body = {title: "hi", search: "person"};
    }   
    console.log('body: ' + JSON.stringify(body));

    return this.http.post('app/php/check.php', body, options)
        .toPromise()
        .then((response) => return response.json())
        .catch(error => {
          console.log( error );
        });
  }

Make sure your content type header is application/x-www-form-urlencoded

Plunker example: https://embed.plnkr.co/UDYDp0gXx5H9OhmMKicL/