Read Angular2 POST data in PHP

I want to connect my angular2 application to my PHP server. Ideally, I want to do this:

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

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

+4
source share
2 answers

Angular HTTP implementation sends data as application/json payload. to read such data from php, you should use this 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 data as application/x-www-form-urlencoded and then be able to read it from PHP $_POST superglobal without any changes to the server code, you should encode the 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, jQuery, for example, works with $ _POST and json objects

it does not work with json object, if you can read data via $_POST , this means that it was sent as application/x-www-form-urlencoded , not application/json , the parameters are set as a simple js object, although ...

+1
source

you can use php: // input for post data with angular2 as follows and json_decode this

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

therefore, this $ arr prints the entire message array and uses it anywhere.

0
source

Source: https://habr.com/ru/post/1265607/


All Articles