【发布时间】:2020-02-02 12:37:34
【问题描述】:
我正在通过多部分请求发送图像和其他表单数据。当我使用 PostMan 调用 api 时,图像已成功添加。但是当我使用角度代码调用相同的 API 时,我从后端收到错误消息。
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;
}));
}
更新: 来自后端的错误:
促销类型无效。
请求负载:
我在这里做错了什么?
【问题讨论】:
-
你遇到了什么错误?
-
@R.Richards 请参阅更新部分。
-
您在控制台中看到错误吗?如果有,它显示了什么?
-
@R.Richards 请查看我上传的最后一张图片。这是 400:错误请求
-
该错误还显示 Invalid Promotion type。因此,无论您发送什么,API 都不喜欢它。 400 错误意味着您没有发送 API 所需的内容。确保您发布的内容符合 API 的预期。
标签: angular forms api post multipart