简体   繁体   English

Django Rest API POST问题

[英]Django Rest API POST issues

I'm trying to build a very simple REST API in Django 1.8 with Django REST Framework in Visual Studio, in which I want to have a single service method to process a JSON, but I can't seem to make a POST: 我正在尝试使用Visual Studio中的Django REST框架在Django 1.8中构建一个非常简单的REST API,我希望在其中使用单个服务方法来处理JSON,但我似乎无法进行POST:

I'm trying to send this simple JSON through Postman, just as a test: 我试图通过Postman发送这个简单的JSON,就像测试一样:

{
   "foo":"bar"
}

with the header: 标题:

Content-Type: application/json

Here's my method: 这是我的方法:

@csrf_exempt
@api_view(['POST'])
def test(request):
    data = request.data
    return HttpResponse(status=200)

But my problem is that request.data is empty. 但我的问题是request.data是空的。 And if instead I try to access request.body, I get 如果相反,我尝试访问request.body,我得到

You cannot access body after reading from request's data stream. 从请求的数据流中读取后,您无法访问正文。

Any ideas what could be the issue here? 任何想法可能是什么问题?

Figured this out somewhat, it seems to be an issue with Visual Studio while in debug mode. 稍微考虑一下,在调试模式下,Visual Studio似乎是一个问题。 If I try to access the request while debugging before calling any Python function on it (such as a simple print, or passing in to a function to parse it), it shows up as an empty QueryDict, otherwise it shows up fine. 如果我在调试任何Python函数之前尝试访问请求(例如一个简单的打印,或者传入一个函数来解析它),它会显示为一个空的QueryDict,否则它会显示正常。

Just a guess: maybe the issue is in Postman? 只是一个猜测:问题可能在Postman?

Try to send POST-request without headers, but with raw JSON (not form-data): 尝试发送没有标头的POST请求,但使用原始JSON(不是表单数据):

在此输入图像描述

This may help Where's my JSON data in my incoming Django request? 这可能有助于我的传入Django请求中的JSON数据在哪里?

Outside of this, make sure the content-type and accept-type are set properly. 除此之外,请确保正确设置content-type和accept-type。 What is the raw response in Postman? Postman的原始回应是什么? Is the security setup properly? 安全设置是否正确?

I have the same problem when using POSTMAN. 使用POSTMAN时遇到同样的问题。

Solved and Credit goes to https://stackoverflow.com/a/31977373/764592 Solved和Credit转到https://stackoverflow.com/a/31977373/764592

Quoted Answer: 引用答案:

Request payload is not converted into JSON format. 请求有效内容未转换为JSON格式。

I am passing my data in Body as x-www-form-urlencoded 我将Body中的数据作为x-www-form-urlencoded传递

在此输入图像描述

You can fix it by using Content-Type as application/x-www-form-urlencoded in request header. 您可以通过在请求标头中使用Content-Type作为application / x-www-form-urlencoded来修复它。

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM