How to post data to server without json but as regular form data

This is my html

<form (ngSubmit) = "signIn()" >
          <ion-list padding>
              
                <ion-item>
                  <ion-label floating>E-mail Address</ion-label>
                  <ion-input [(ngModel)] ="loginData.email" name="email" type="text" value="marsh002@gmail.com"></ion-input>
                </ion-item>
              
                <ion-item>
                  <ion-label floating>Password</ion-label>
                  <ion-input [(ngModel)]="loginData.password" name="password" type="password" value="Demo1234"></ion-input>
                </ion-item>

                <ion-item>
                    <button color="laundryPrimaryLight" [disabled]="!loginData.email || !loginData.password"  ion-button large full round>Sign In</button>
                </ion-item> 
              
               
          </ion-list>
        </form>

My typescript file

loginData = {"email":"","password":""};

signIn()
  {
      let key = 'integration/customer/token';
      
       this.ApiServiceProvider.postData(this.loginData,key).then((result) => {
   
         this.loginResponse = result;
         console.log(this.loginResponse);
         localStorage.setItem('user',JSON.stringify(this.loginResponse));     
         
   
       }, (err) => {
           // Error message
        });
   
     
  }

And finaly my provider

 postData(data,key) {
    console.log('in api');
    console.log(data);

    return new Promise((resolve,reject) => {

      let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'});   
      let body = data.toString();  
      console.log('body--'+body);

      this.http.post(baseUrl+key,body,{headers:headers}).subscribe(res => {
        resolve(res.json());

      },(err) => {

          reject(err);

      });
      

    }); 

  }

Don’t: manually stringify the body, manually set content type
Do: use URLSearchParams

1 Like