【问题标题】:Angular2 Http protocol might not be posting properlyAngular2 Http 协议可能无法正确发布
【发布时间】:2016-12-14 01:16:01
【问题描述】:

这是我的 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"
  }
]

与萤火虫。


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

是不是我做错了什么?

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



更新:

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

【问题讨论】:

  • 您是返回来自check.php 的响应,还是只是打印请求?
  • @EamonnMcEvoy 刚刚打印。这就是您从 php 脚本接收响应的方式不?

标签: angular typescript angular2-services angular2-http


【解决方案1】:

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

这是一个如何从函数中检索输出的示例。由于我用于发布数据的测试 API,该示例使用 JSON 输出。一个字符串将是相同的,只需更改返回部分。

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

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

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

【讨论】:

  • 我的代码看起来和你的没什么不同......但是当我只是 echo 'hi'; 它给了我一个回报,所以它只是没有收到帖子或其他东西。哦,好吧,我会继续尝试的。
  • 当我使用 $.ajax 时,我肯定会找回数据
  • 您能否打开开发者工具并查看网络选项卡并查看来自 http 的 Ajax 请求返回的内容。
  • 所以从 firebug lite (chrome) 我可以看到它按预期发布数据。但是,响应只是一个空数组。
  • 好的,所以响应有 php 问题?如果您直接在浏览器中尝试使用 url 会发生什么,比如说获取值 app/php/check.php?test=string
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-19
  • 1970-01-01
  • 2021-06-03
  • 2017-02-12
  • 1970-01-01
  • 1970-01-01
  • 2017-02-08
相关资源
最近更新 更多