如何以角度发送类似邮递员的application / x-www-form-urlencoded邮寄请求

时间:2019-05-12 11:37:05

标签: angular postman angular-httpclient

我为Django API项目编写了一个基于角度的客户端应用程序。端点之一接受application / x-www-form-urlencoded格式的请求,因为它包含文件和字符串数据,而且我敢肯定它在服务器端也能正常工作-我已经准备好了application / x-www POSTMAN -form-urlencoded请求:

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”返回“ 415不支持的媒体类型”

这是我发送请求的方式:

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设置为其他类型时,为什么请求的Form Data是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);

2 个答案:

答案 0 :(得分:0)

尝试研究Axios库https://github.com/axios/axios

如果向下滚动,您会注意到需要sou的示例。您可以在Angular应用程序中使用Axios,而不会出现问题。

答案 1 :(得分:-1)

将您的原始代码更改为

    return this.httpClient.post<DataFile>(this.apiEndpoints.datafilesCreateEndpoint(), new HttpParams({ fromObject: formGroup.value }));

FormData 被发送为 multipart/form-data,而不是 application/x-www-form-urlencoded

相关问题