在PHP中读取Angular2 POST数据

时间:2016-12-15 12:01:48

标签: php angular

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

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

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

2 个答案:

答案 0 :(得分: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对象虽然......

答案 1 :(得分:0)

你可以使用php://输入像这样的angular2和json_decode这样的帖子数据

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

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

相关问题