简体   繁体   中英

Unable to post variable through http.post() in angular 4

I'm getting issue in angular 4 .... I am building hybrid app using ionic 3.

I have to use php as server side language for APIs, I am having issue in posting variables to http.post() request ...

variables are not passed to php file.

Method I'm using to call API from home.ts is:

var json = {var1: 'test'};

var params = 'json='+json;

let headers = new Headers();

headers.append('Content-Type', 'application/json');

http.post("http://example.com/infoarray.php", params, headers ).subscribe (re => {
console.log(re)
})

I'm able to get response from API just fine but the problem is I can't pass the value of variable 'var1' to my API on infoarray.php I'm encoding the request to json ... but didn't get variables

  1. Check your PHP code, may be you are missing to get JSON content from Post.

     $data = json_decode(file_get_contents('php://input'), true); print_r($data); echo $data["param"]; 
  2. Otherwise try to add params in form data

     let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); let options = new RequestOptions({ headers: headers }); // Create a request option let url = "SERVER_URL"; let body = 'param1='+value1+'&param2=' +value2; this.http.post(url, body, options) 

Use JSON.stringify() method while processing the params:

var json = {var1: 'test'};

var params = 'json='+JSON.stringify(json);

Your params = 'json='+json will actually result to this: "json=[object Object]". That's because you didn't stringify the object first, which is done as so:

var params = 'json=' + JSON.stringify(json); // "json={"var1":"test"}"

Use JSON.stringify() and put your headers in RequestOptions class

let headers = new Headers();
    headers.append('Content-Type', 'application/json');
let requestOpt = new RequestOptions({ headers: headers });
    const bodyStr = JSON.stringify({var: value});

this.http
    .post(this.vocabularyPostUrl, bodyStr, requestOpt)

You have to stringify the object. Otherwise you will end in getting "[object][object]" rather than "{var1: 'test'}" .

JSON.stringify(json);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM