django-rest-framework 接受 JSON 数据?

django-rest-framework accept JSON data?

我使用 创建了 RESTFul API。用户端点是:/api/v1/users

我想创建一个新用户,所以我以 JSON 格式发送用户数据:

{
    "username": "Test1",
    "email": "test1@gmail.com",
    "first_name": "Test1",
    "last_name": "Test2",
    "password":"12121212"
}

我正在使用 Google Chrome 扩展 Postman 来测试 API。但是,发送请求后,用户数据并未保存。响应包含此错误:

{
    "detail": "Unsupported media type \"text/plain;charset=UTF-8\" in request."
}

这是请求详细信息在 Postman 中的样子:

您需要通过设置适当的 headers 来定义内容类型。对于 Postman,您需要在 url 字段下设置以下值:

Header: "Content-Type"

值:application/json

您错过了在 headers 部分添加 Content-Type header。只需将 Content-Type header 设置为 application/json 即可。

见下图:

此外,您可能还需要在 header 中包含一个 CSRF 令牌,以防您在使用 Postman 发出 POST 请求时遇到错误 {"detail": "CSRF Failed: CSRF token missing or incorrect."}。在这种情况下,添加一个 X-CSRFToken header 也将值作为 CSRF 令牌值。

你需要做两步来完成这个问题:

  1. 添加 Content-Type header 和 application/json
  2. Token {YOUR_CUSTOM_TOKEN}值添加Authorizationheader传递CSRFToken

注意:如果你想用session认证,你不需要做第二步,但如果你想使用这个API对于移动设备,您必须将授权 header 传递给服务器

希望对您有所帮助

我发布这个答案以防有人遇到像我这样的问题。

我正在使用 Angular 2 开发 Front-End 应用程序,并使用 Django Rest 制作的 API Framework 和我曾经使用以下 headers:

发送请求
'Content-Type': 'application/json'

它工作正常,直到我在 Fire Fox 上尝试它,但我无法加载所需的数据,我通过添加以下 headers[ 解决了这个问题=16=]

'Content-Type': 'application/json',
'Accept': 'application/json'

这里有一个解释,Content-Type tells the server what is the content type of data is while Accept 告诉它客户端将接受什么内容类型。

这里有一个关于这个问题的明确答案:

https://webmasters.stackexchange.com/questions/31212/difference-between-the-accept-and-content-type-http-headers

我必须添加以下内容才能使其正常工作(我在客户端使用 node-fetch 顺便说一句来执行 POST):

supportHeaderParams: true,
headers: { "Content-Type": "application/json; charset=UTF-8" },