Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic 2 - Http POST body parameters not being sent

I am using Ionic 2 Beta 11. I am trying to send a request to an external API which will return a JSON response. I have overcome CORS issues and I am communicating with the API however I can not send the body information that is required. I have tried formatting the body variable in the following ways, each with no success:

As an object: {email: this.email, password: this.password}

As a stringified object: JSON.stringify({email: this.email, password: this.password})

As a string: 'email=' + this.email + '&password=' + this.password

Here is my code:

import {Component}                                      from '@angular/core';
import {NavController, MenuController}                  from 'ionic-angular';
import {Http, Headers, RequestOptions}                  from '@angular/http';
import 'rxjs/Rx';

@Component({
  templateUrl: 'build/pages/login/login.html'
})
export class LoginPage {
  nav: NavController;    
  username: string;
  password: string;

  constructor(nav: NavController, private http: Http) {
    this.nav = nav;
  }

  doLogin() {
    let body = JSON.stringify({
      email: this.username,
      password: this.password });
    let headers = new Headers({
      'NDAPI-Key': 'XXXXXXXXXX',
      'NDAPI-Host': 'XXXXXXXXXXX' });
    let options = new RequestOptions({ headers: headers });

    this.http
        .post('/api', body, options)
        .map(res => res.json())
        .subscribe(
            data => {
              console.log(data);
            },
            err => {
              console.log("ERROR!: ", err);
            }
        );
  }
}
like image 729
Ian Holden Avatar asked Aug 17 '16 11:08

Ian Holden


2 Answers

I am new to Ionic 2 but after long search Form data option worked for me like below

let headers = new Headers({ 'Content-Type': 'application/json' });
    let body = new FormData();
    body.append('username', username);
    body.append('password', password);
    console.log(body);
    console.log(headers);
    return this.http.post('http://api/v1/get_user',body,headers).map((res: Response) => res.json());
like image 144
Ali Farhan Avatar answered Oct 01 '22 20:10

Ali Farhan


I had the same problem that my parameters were not posted to my PHP Server. I changed parameters to raw format (shown in my body variable), and it started working. See sample code below.

    let headers = new Headers({
        'Content-Type': 'application/x-www-form-urlencoded'
    });
    let options = new RequestOptions({
        headers: headers
    });
    // TODO: Encode the values using encodeURIComponent().
    let body = 'email=' + email + '&password=' + password;
like image 27
Hasnat Safder Avatar answered Oct 01 '22 20:10

Hasnat Safder