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

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.

register(username: string, email: string, password: string, givenname: string, surname: string){
    var headers = new Headers();
    headers.append('content-type', 'application/json;charset=UTF-8');
    headers.append('Access-Control-Allow-Origin','*');
    let options= new RequestOptions({headers: headers});
  
    var url = 'https://api.stormpath.com/v1/tenants/1QI0gxrvZNfYAFsamRTwbf/accounts';

    var data = JSON.stringify({
      surname: surname,
      username: username,
      givenName: givenname,
      email: email,
      password: password
    });

    this.http.post(url, data, options).map(res=>res.json()).subscribe(data=>{
      console.log(data)
    }, err=>{
      console.log("Error!:", err.json());
    });
 }

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?



Solution 1:[1]

I had the same issue , go to chrome extensions and search for the plugin CORS and add the best plugin you like ,then enable the plugin it will work

Solution 2:[2]

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;
    }
  }
});

Solution 3:[3]

In the Ionic latest versions if you are using ionic serve commnad then you must have to use Proxies to prevent Preflight and CORS Issues,

First add API path and URL in ionic.config.json file like

{
  "name": "APP-NAME",
  "app_id": "",
  "proxies": [
    {
      "path": "/accounts",
      "proxyUrl": "https://api.stormpath.com/v1/tenants/1QI0gxrvZNfYAFsamRTwbf/accounts"
    }
  ]
}

Now, while calling your API from http use the /accounts URL instead of the https://api.stormpath.com/v1... like,

....
    var url = '/accounts'; // use the Proxy Path here instead of Stormpath API URL

    var data = JSON.stringify({
      surname: surname,
      username: username,
      givenName: givenname,
      email: email,
      password: password
    });

    this.http.post(url, data, options).map(res=>res.json()).subscribe(data=>{
      console.log(data)
    }, err=>{
      console.log("Error!:", err.json());
    });
....

After making the above changes you must rerun command ionic serve.

Still, if you are getting issues then refer Handling CORS Issues In Ionic

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ameen Maheen
Solution 2 Rohan Kumar
Solution 3 Rohan Kumar