Angular2 Http 协议可能无法正确发布

Angular2 Http protocol might not be posting properly

这是我的 http 代码:

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

我不确定服务器是否正确接收数据,但我确定它正在发布我所看到的内容:

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

和 firebug。


在我的 php 文件中,我所做的只是 print_r($_REQUEST),但是 returns 只是一个空数组。

我做错了什么吗?

奖金问题: 除了 .json().text() 响应之外,还有其他数据提取功能吗?



更新:

有趣的是,如果我使用 url app/php/check.php?fruit=apple 会有响应。有人知道差异吗?

服务器应该正在接收您的 body 变量中的数据。

这是一个示例,说明您应该如何从函数中检索输出。该示例使用 JSON 输出,但由于测试 API 我正在使用 post 数据。字符串将是相同的,只需更改 return 部分。

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

确保您的内容类型 header 是 application/x-www-form-urlencoded

Plunker 示例: https://embed.plnkr.co/UDYDp0gXx5H9OhmMKicL/