在PHP中读取Angular2 POST数据

4

我希望将我的Angular2应用程序与我的PHP后端连接。理想情况下,我希望做到以下几点:

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

问题是,当我这样做时,在PHP中我的$_POST为空。我该怎么做才能使其正常工作?

在这里很好地解释了:http://stackoverflow.com/questions/36897266/fetch-and-insert-data-into-mysql-using-angularjs - Sanoj Sharma
那肯定不是唯一的解决方法吧?从 php://input 读取?我的意思是,例如用 jQuery,它会使用 $_POST 和 json 对象。 - DannySwekker
@DannySwekker — jQuery默认不会将请求格式化为JSON。它使用的是application/x-www-form-urlencoded编码。您还应该澄清您对JSON的明显误解 - Quentin
2个回答

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对象

如果你可以通过$_POST读取数据,那就意味着数据被发送为application/x-www-form-urlencoded,而不是application/json。参数被设置为一个普通的js对象,而非json对象。


有没有任何方法可以在每个请求中都完成这项工作?我感到有些困惑,因为我觉得每个php应用程序都应该遇到这个问题,对吧?如果他们想要使用angularjs的话。 - DannySwekker
只需创建一个自定义服务来包装 http 调用。我认为这并不是什么问题,因为大多数人使用 JSON API 与服务器通信。 - n00dl3

0

您可以在Angular2中使用php://input来获取POST数据,然后使用json_decode解析数据。

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接