Angular 4 - Django:“请求中不支持媒体类型“text/plain”。”

Mik*_*sus 5 json django-rest-framework typescript angular

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

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

我认为我的 API 配置是正确的,因为我进行了研究,发现了同样的错误,而且问题出在 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) => {});
}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 8

正如错误“您使用了错误的媒体类型”中所指定的那样。

将其更改为application/json

在此输入图像描述


Séb*_*ien 1

The body of your HTTP request must be an object:

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

And there is no need to stringify it:

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) => {});
}
Run Code Online (Sandbox Code Playgroud)

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