我希望将我的Angular2应用程序与我的PHP后端连接。理想情况下,我希望做到以下几点:
this.http.post('/users/create', {email: email, password: password});
问题是,当我这样做时,在PHP中我的
$_POST
为空。我该怎么做才能使其正常工作?我希望将我的Angular2应用程序与我的PHP后端连接。理想情况下,我希望做到以下几点:
this.http.post('/users/create', {email: email, password: password});
$_POST
为空。我该怎么做才能使其正常工作?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对象。
http
调用。我认为这并不是什么问题,因为大多数人使用 JSON API 与服务器通信。 - n00dl3您可以在Angular2中使用php://input来获取POST数据,然后使用json_decode解析数据。
$arr = json_decode(file_get_contents('php://input'),TRUE);
echo "<pre>";print_r($arr);exit;
所以通过这个 $arr,可以打印整个帖子数组,并在任何需要的地方使用它。