【发布时间】:2019-09-29 14:48:53
【问题描述】:
我为 Django API 项目编写了一个基于 Angular 的客户端应用程序。其中一个端点接受 application/x-www-form-urlencoded 格式的请求,因为它包含文件和字符串数据,我很确定它在服务器端工作得很好 - 我已经准备了一个 application/x-www -form-urlencoded 使用 POSTMAN 的请求:
HEADERS:
Content-Type: application/x-www-form-urlencoded
BODY (form-data):
experiment: http://127.0.0.1:8000/api/v1/experiments/6/
measurement: http://127.0.0.1:8000/api/v1/measurements/4/
variable:
x_axis: X_AXIS
y_axis: Y_AXIS
file_object: // here I've changed the field type and chose the .txt file
当然服务器响应正确,并且文件已添加。确切的请求正文如下所示:
experiment=http://127.0.0.1:8000/api/v1/experiments/6/measurement=http://127.0.0.1:8000/api/v1/measurements/4/variable=x_axis=os Xy_axis=os Yfile_obj=[object Object]
但现在,事情变得越来越复杂。我尝试使用响应式表单和 HttpClient 在 Angular 中准备相同的请求。假设响应式表单本身可以正常工作,但是发送请求时将“Content-Type”设置为:
- 'application/x-www-form-urlencoded' 返回'500 Internal Server Error',并且
- 'multipart/data-form' return '415 Unsupported Media Type'
这是我发送请求的方式:
post(formGroup: FormGroup): Observable<DataFile> {
const httpOption = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})
};
return this.httpClient.post<DataFile>(this.apiEndpoints.datafilesCreateEndpoint(), formGroup.value, httpOption);
}
下面是具体请求的样子:
{"experiment":"http://127.0.0.1:8000/api/v1/experiments/6/","measurement":"http://127.0.0.1:8000/api/v1/measurements/4/","variable":" ","x_axis":"X AXIS","y_axis":"Y AXIS","file_obj":"C:\\fakepath\\navon.txt"}
当我将 Content-Type 设置为其他类型时,不知道为什么请求的表单数据是 JSON。会不会是这个问题的原因?
@UPDATE 解决方案
我已经从 post 函数中删除了 httpOptions,让 Angular 自动传递 Content-Type。然后,我没有将 FormGroup.value 传递给 httpClient 的帖子,而是创建了 FormData 并将其传递。
我的 POST 函数如下所示:
post(experiment: SharedModel, measurement: SharedModel, andOtherDataINeed: any): Observable<DataFile> {
const fd = new FormData();
fd.append('experiment', experiment as any);
...
fd.append('file_obj', file);
return this.httpClient.post<DataFile>(this.apiEndpoints.datafilesCreateEndpoint(), fd);
【问题讨论】:
-
@FrancescoFortin 确实向前迈进了一步,感谢您的回答,但表单的文件输入标签返回“假”文件路径而不是我预期的 File 对象 - 需要了解如何处理这个。
-
将该文件转换为 base64 编码并改为发布该 base64。
-
据我所知,
FormData以multipart/form-data发送。如果你想要application/x-www-form-urlencoded,请使用new HttpParams({ fromObject: formGroup.value })。
标签: angular postman angular-httpclient