当前位置: 首页 > 知识库问答 >
问题:

如何发送邮递员般的,应用程序/x-www-form-urlencoded帖子请求角

郁权
2023-03-14

我为Django API项目编写了一个基于angular的客户端应用程序。其中一个endpoint接受application/x-www-form-urlencoded格式的请求,因为它同时包含文件和字符串数据,我很确定它在服务器端工作正常——我已经使用POSTMAN准备了一个application/x-www-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内部服务器错误”,并且
  • “多部分/数据表单”返回“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设置为不同的内容类型时,不知道为什么请求的表单数据是JSON。这可能是这个问题的原因吗?

@更新解决方案

我已经从post函数中删除了httpOptions,让Angular自动传递内容类型。然后,而不是通过FormGroup。对于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个答案

华季同
2023-03-14

将原始代码更改为

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

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

施永宁
2023-03-14

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

如果您向下滚动,您会注意到您需要的示例。您可以毫无问题地在Angular应用程序中使用Axios。

 类似资料: