Md Sultanul Arefin
Md Sultanul Arefin

Reputation: 11

convert JSON to multipart/form-data angular/ionic

When i send POST request form POSTMAN and get correct response

This is Form-Data Body request of Postman POST.

ENDPOINT : https://cholas.in/wp-json/digits/v1/send_otp

Success Respond when i request with Form-Data

When i send POST request from POSTMAN and get Wrong response

JSON Body request

Content-Type : multipart/form-data;

When i send POST request from POSTMAN and get Wrong response

Content-Type : multipart/form-data; header with json body :

Content-Type : multipart/form-data; header with json body

Angular and IONIC code when i send post request

    const formData = new FormData();
    let httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'multipart/form-data; charset=UTF-8'
        })
    };
  
    
    formData.append('countrycode',this.formSMS.countrycode);
    formData.append('mobileNo',this.formSMS.mobileNo);
    formData.append('type',this.formSMS.type);
    formData.append('whatsapp',this.formSMS.whatsapp);
    // rest data to the form.
    //Object.keys(restObj).forEach(key => {
    //  formData.append(key, restObj[key]);
    //});
    console.log(formData);
    // Send it.
    return this.http.post(Url, formData, httpOptions)
      .toPromise()
      .catch((e) => {
          console.log(e);
        // handle me
      });

But i get Wrong Response that i don't want.

angular/ionic wrong response that i don't want

NB: OTP Providers Documentation NOTE: The request should be sent as POST Parameters in Body

What will be the right wey in IONIC/ANGULAR/POSTMAN(JSON Type) to getting right Resonse that i getting as POSTMAN first Screenshot ?

Upvotes: 1

Views: 2584

Answers (1)

Rahul Cv
Rahul Cv

Reputation: 725

You dont need to pass httpOptions in post data since You are passsing Form data angular will handle that for you

const formData = new FormData();
    let httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'multipart/form-data; charset=UTF-8'
        })
    };
  
    
    formData.append('countrycode',this.formSMS.countrycode);
    formData.append('mobileNo',this.formSMS.mobileNo);
    formData.append('type',this.formSMS.type);
    formData.append('whatsapp',this.formSMS.whatsapp);
    // rest data to the form.
    //Object.keys(restObj).forEach(key => {
    //  formData.append(key, restObj[key]);
    //});
    console.log(formData);
    // Send it.
    return this.http.post(Url, formData)
      .toPromise()
      .catch((e) => {
          console.log(e);
        // handle me
      });

Below stackbliz contains the solution please refer https://stackblitz.com/edit/angular-http-get-examples-f28x9u?file=app%2Fapp.component.ts

Upvotes: 0

Related Questions