HTTP post request server could not receive params

I’m trying to use Ionic 2 build app and do a http post to the server.

The server could receive the post request, and send the return message. However, the param is not passed to the server.

I tried to write a simple POST html page to test the browser and it works after I enable browser’s CROS setting.

Below is my code for the post

import { Injectable, Component } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/Rx';

@Injectable()
@Component({
})
export class UserData{

  constructor(public http: Http) {
  }

  postSetting(uid, setting) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    let data =JSON.stringify({
      uid: uid,
      setting: setting
    });

    return this.http.post('xxx/api/update_user'
                          , data
                          , {headers: headers})
                    .map(res => res.json())
                    .subscribe(data => {
                       console.log(JSON.stringify(data));
                    });
  }

I also tried

headers.append('Content-Type', 'application/x-www-form-urlencoded');
...
data = 'uid='+uid+'&setting='+setting;

which is also not working, the http param is still empty.

My questions:

  1. Will this issue related to the server side? (I could receive the error message from the server saying that param is missing)
  2. Anyone have some idea about how to solve this issue? Is this related to CORS?

Thanks in advance

1 Like

try this

import { Http, Response,Request } from '@angular/http';
     buildProduct(stringify_params){
            let postParams={
              form_product: JSON.stringify(stringify_params)
            }
            return new Promise((resolve, reject) => {
            this.http.post(`${this.baseUrl}/product/new.json`,postParams)
                .subscribe(res => resolve(res.json()), (err) => {
            reject(err);
          });

        });   
    }

What do you use on server side? How do you parse the parameters on Serverside?

General observations:

  • you don’t need to explicitly set content type in 99.9% of cases; Angular will use the type of the body to do it for you, leading to:
  • don’t stringify parameters yourself; pass an object for JSON and a URLSearchParams for form-encoded
  • there is no need for explicitly instantiating Promises here

The issue is fixed now and it is due to some unexpected problem on server side code.

The ionic code works okay.