【问题标题】:Read Angular2 POST data in PHP [duplicate]在 PHP 中读取 Angular2 POST 数据 [重复]
【发布时间】:2017-05-01 00:41:48
【问题描述】:

我想将我的 angular2 应用程序连接到我的 PHP 后端。理想情况下,我想这样做:

this.http.post('/users/create', {email: email, password: password});

问题是,当我这样做时,我的$_POST 在 PHP 中是空的。我必须怎么做才能完成这项工作?

【问题讨论】:

标签: php angular


【解决方案1】:

Angular 的 http 实现将数据作为application/json 有效负载发送。要从 php 中读取此类数据,您必须使用这种代码:

$data = json_decode(file_get_contents("php://input"));
// you can even override the `$_POST` superglobal if you want :
$_POST = json_decode(file_get_contents("php://input"));

如果您想以application/x-www-form-urlencoded 发送您的数据,然后能够从php 的$_POST 超全局读取它而不对您的服务器代码进行任何更改,您需要对您的数据进行编码。

const body = new URLSearchParams();
Object.keys(value).forEach(key => {
  body.set(key, value[key]);
}

let headers = new Headers();
headers.append('Content-Type','application/x-www-form-urlencoded');
this._http.post(this._contactUrl, body.toString(), {headers}).subscribe(res => console.log(res));

我的意思是使用 jQuery,例如它适用于 $_POST 和 json 对象

它不适用于json对象,如果您可以通过$_POST读取数据,则表示它已作为application/x-www-form-urlencoded发送,而不是application/json,但参数设置为普通js对象...

【讨论】:

  • 有没有办法让每个请求都完成这个?当我觉得每个 php 应用程序都应该有这个问题时,我很困惑它是如此的麻烦?如果他们想使用 angularjs
  • 只需创建一个自定义服务来包装http 调用。我认为这不是什么大问题,因为大多数人使用 JSON API 与服务器通信。
【解决方案2】:

您可以将 php://input 用于像这样的 angular2 和 json_decode 这样的发布数据

$arr = json_decode(file_get_contents('php://input'),TRUE);
echo "<pre>";print_r($arr);exit;

所以通过这个 $arr 打印整个帖子数组并在任何你想要的地方使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-08
    • 2012-04-16
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    相关资源
    最近更新 更多