以角度发送多部分/表单数据POST API请求

问题描述 投票:0回答:1

我正在通过多部分请求发送图像和其他表单数据。当我使用PostMan调用api时,图像已成功添加。但是,当我使用角度代码调用相同的API时,后端出现错误。

enter image description here

Component.ts] >>

addOffer() {
    this.formData = new FormData();
    this.formData.append('promotion', this.file, this.file.name);
    this.formData.append("main_text", this.offerAddForm.controls['title'].value);
    this.formData.append("type", '1');
    this.formData.append("footer_text", 'rdy');

    this._addOfferService.addOffer(this.formData)
      .pipe(first())
        .subscribe(
            data => {
              console.log("Yo yo "+data);
            },
            error => {
              console.log("An Error Occurred add notify ", error);
            });
  }

Service.ts

] >>
addOffer(formData) {
    const token = this.authService.getToken();
    let headerOptions = new HttpHeaders({
      'Content-Type': 'multipart/form-data',
      'Authorization': 'Bearer '+token
    });

    const url = environment.baseURL + 'promotions';
    return this.http.post<any>(url, formData, {headers: headerOptions})
      .pipe(map(response => {
        return response;
      }));
  }

更新:来自后端的错误:

无效的促销类型。

请求有效载荷:

] >>

enter image description here

enter image description here

我在这里做错了什么?

我正在通过多部分请求发送图像和其他表单数据。当我使用PostMan调用api时,图像已成功添加。但是,当我调用相同的API时,我从后端得到一个错误...

 let urlSearchParams = new URLSearchParams();
    urlSearchParams.append('cc', this.PayElement.CC);

    // alert(urlSearchParams.toString());
    this.appService.sendToOtherService('https://dddddd?ggg=dfdf&ddgg=5555, 
      urlSearchParams.toString()).then(res2 => {
//

    }).catch(res3 => {
     //
    });



sendToOtherService(url: string, data: any): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
    let options = new RequestOptions({headers: headers});
    return this.http.post(url, data, options).toPromise()
      .then(response => response.json() as any)
      .catch(this.handleError);
  }
angular forms api post multipart
1个回答
0
投票
 let urlSearchParams = new URLSearchParams();
    urlSearchParams.append('cc', this.PayElement.CC);

    // alert(urlSearchParams.toString());
    this.appService.sendToOtherService('https://dddddd?ggg=dfdf&ddgg=5555, 
      urlSearchParams.toString()).then(res2 => {
//

    }).catch(res3 => {
     //
    });



sendToOtherService(url: string, data: any): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
    let options = new RequestOptions({headers: headers});
    return this.http.post(url, data, options).toPromise()
      .then(response => response.json() as any)
      .catch(this.handleError);
  }
© www.soinside.com 2019 - 2024. All rights reserved.