在 PHP 中读取 Angular2 POST 数据 [英] Read Angular2 POST data in PHP

查看:24
本文介绍了在 PHP 中读取 Angular2 POST 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

问题是,当我这样做时,我的 $_POST 在 PHP 中是空的.我必须做什么才能使这项工作发挥作用?

解决方案

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

$data = json_decode(file_get_contents("php://input"));//如果需要,您甚至可以覆盖 `$_POST` 超全局变量:$_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]);}让标题=新标题();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 对象...

I want to connect my angular2 app to my PHP backend. Ideally I want to do this:

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

The problem is, when I do this my $_POST is empty in PHP. What must I do to make this work?

解决方案

Angular's http implementation sends data as an application/json payload. to read such data from php, you have to use this kind of code :

$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"));

if you want to send your data as application/x-www-form-urlencoded and then be able to read it from php's $_POST superglobal without any change to your server code, you need to encode your data as such.

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

I mean with jQuery for example it works with $_POST and json objects

it does not work with json object, if you can read data via $_POST, it means it has been sent as application/x-www-form-urlencoded, not application/json, parameters are set as a plain js object though...

这篇关于在 PHP 中读取 Angular2 POST 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆