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);
}
);
}
}
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());
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With