简体   繁体   中英

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

当我使用表单数据请求时成功响应

When i send POST request from POSTMAN and get Wrong response

JSON Body request

Content-Type : multipart/form-data;

当我从 POSTMAN 发送 POST 请求并得到错误的响应时

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

内容类型:多部分/表单数据;带有 json 正文的标头

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.

我不想要的角度/离子错误响应

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM