简体   繁体   中英

Angular2 http.post won't send JSON data to API

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM