【问题标题】:Angular 4 - Django: "Unsupported media type \"text/plain\" in request."Angular 4 - Django:“请求中不支持的媒体类型 \"text/plain\"。”
【发布时间】:2018-07-12 10:11:08
【问题描述】:

我正在使用网络应用程序。我在 Angular 4 中使用前端,在 Django Rest 中使用后端。

当我想从 API 接收信息时,它工作得很好,但是当我尝试使用 API 发送数据以保存在数据库中时,我遇到了这个错误:"Unsupported media type \"text/plain\" in request."

我认为我的 API 配置是正确的,因为我一直在研究并且发现同样的错误并且问题出在 Angular 中。我已经尝试了所有我发现的方法,但对我没有任何作用。

这是我的 Angular 代码:

enviar() {
    var body = '"schema_name":"pruebanm","fecha_alta":"2018-02-01","nombre":"cliente","ubicacion":"prueba","telefono":"1234567","correo":"cliente@prueba.com","activo":true';
    this.http.post("http://tenant1.intrainingls.com:8000/viewSets/cliente/", JSON.stringify(body)).subscribe((data) => {});
}

我希望有人可以帮助我找到解决方案。 (正文中的数据正在尝试)

PD。如果您需要更多信息,请告诉我。

【问题讨论】:

    标签: json angular typescript django-rest-framework


    【解决方案1】:

    如错误“您使用了错误的媒体类型”中所述。

    改成application/json:

    【讨论】:

      【解决方案2】:

      你的 HTTP 请求的主体必须是一个对象:

      var body = { "schema_name":"pruebanm","fecha_alta":"2018-02-01","nombre":"cliente","ubicacion":"prueba","telefono":"1234567","correo":"cliente@prueba.com","activo":true };
      

      而且没有必要对其进行字符串化:

      enviar() {
          var body = '"schema_name":"pruebanm","fecha_alta":"2018-02-01","nombre":"cliente","ubicacion":"prueba","telefono":"1234567","correo":"cliente@prueba.com","activo":true';
          this.http.post("http://tenant1.intrainingls.com:8000/viewSets/cliente/", body).subscribe((data) => {});
      }
      

      https://angular.io/guide/http#making-a-post-request

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-05
        • 1970-01-01
        • 2015-03-30
        • 2021-02-28
        • 2013-01-30
        • 1970-01-01
        • 2014-11-14
        • 2022-06-25
        相关资源
        最近更新 更多