How to use the http post method on ionic 2 and Angular 2?

Peter Berzins picture Peter Berzins · Dec 5, 2016 · Viewed 7k times · Source

I am now creating the Ionic 2 app to register and authenticate to Stormpath. When I registered the user I used the http post method. Following function is in provider there.

And using this function code is as following.

signup(form){

    console.log('Pressed Signup button.')

    let username = form.value.username,
      email = form.value.email,
      password = form.value.password,
      givenName = form.value.givenName,
      surname = form.value.surname;

    this.stormpathService.register(username, email, password, givenName, surname);

    this.navCtrl.pop();
  }

The HTML file is :

<ion-content padding>
  <form #signupForm="ngForm" (ngSubmit)="signup(signupForm)">
    <ion-list style="margin-bottom: 25%;">
      <ion-item>
        <ion-label floating>GivenName</ion-label>
        <ion-input [(ngModel)]="givenName" name="givenName" type="text" required=""></ion-input>
      </ion-item>
      <ion-item>
        <ion-label floating>SurName</ion-label>
        <ion-input [(ngModel)]="surname" name="surname" type="text" required=""></ion-input>
      </ion-item>
      <ion-item>
        <ion-label floating>Username</ion-label>
        <ion-input [(ngModel)]="username" name="username" type="text" required=""></ion-input>
      </ion-item>

      <ion-item>
        <ion-label floating>Email</ion-label>
        <ion-input [(ngModel)]="email" name="email" type="text" ></ion-input>
      </ion-item>

      <ion-item>
        <ion-label floating>Password</ion-label>
        <ion-input [(ngModel)]="password" name="password" type="password" required=""></ion-input>
      </ion-item>
    </ion-list>

    <div style="margin-bottom: 8%;">
      <button ion-button type="submit" color="light" full > Sign up </button>
    </div>

  </form>
</ion-content>

Error screen is : enter image description here

Why I don't get response from stormpath server?

Answer

Simon Berton picture Simon Berton · Mar 10, 2017

Can you try to transform your http request and add your headers?

$http.post('yoururl', {
    foo: 'bar'
    }, {
    transformRequest: {
        body: function(data, headersGetter) {
        return myTransformFn(data);
    },
    headers: function(data, headersGetter) {
        var headers = headersGetter();
        headers['Content-Type'] = 'x-www-form-urlencoded';
        return headers;
    }
  }
});