2017-09-01 65 views
0

我一直在试图弄清楚这一点几乎每天,没有运气。 我有一个简单http.post要求:Angular2 http.post不会JSON数据发送到API

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

    } 

我条纹的API端点降到最低:不.htacces,只是php文件这个简单的代码:

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

我不断收到空数组返回。但是,如果我改变这样的代码:

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

然后$ _REQUEST对象得到我的数据。我错过了什么?

+0

如果您使用URL参数获得结果,那么它与php相关,而不是角度相关!我不熟悉PHP,但也许你应该将它设置为接受JSON post请求 – trichetriche

+0

'JSON.stringify'会返回一个JSON字符串,但你需要的是https://stackoverflow.com/questions/1714786/query-string -encoding--A-JavaScript的对象的 –

回答

1

PHP $ _REQUEST是:

的关联数组默认包含_GET,$ _ POST和$ _COOKIE

$_POST

关联数组内容的使用应用程序/ x-WWW窗体-urlencoded或多部分/格式的数据作为在请求中的HTTP内容类型时通过HTTP POST方法传递给当前脚本变量。

PHP无法解析的“application/JSON”的数据,该解决方法是php wrapper,通过使用“的file_get_contents(‘PHP://输入’)”可以以这种方式从读取请求实体主体中的数据:

$body = file_get_contents('php://input'); 
$data = json_decode($body); 
print_r($data); // here is what you need