Django(DRF)不显示CORS发布的数据(来自React frontend)

2024-10-01 00:26:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用React前端,与DRF(Django Rest Framework)后端通信。在

目前两者都运行在自己的开发服务器上,因此它们运行在不同的域上。在

我将数据从前端发送到后端,使用POST方法,使用Axios发送请求。在

我使用的代码如下所示。在

问题:

Django似乎没有收到发布的数据。在

正如您在下面的代码中看到的,我试图打印出接收到的数据,但这是我在控制台中看到的:

[12/Jun/2018 13:33:17] "OPTIONS /order/create HTTP/1.1" 200 0

request.POST:

<QueryDict: {}>

[12/Jun/2018 13:55:47] "POST /order/create HTTP/1.1" 200 2

(这似乎是正常的,打印信息首先出现在控制台中,然后是POST请求的行。即使print语句是由POST请求执行的,而不是由OPTIONS请求执行的。这让我有点困惑。)

我已经试过了:

我尝试添加以下标题:

^{2}$

我试着补充:

withCredentials: true

(在我的代码中注释掉了,如果这篇文章在底部)

最初,这给了我一个关于预飞请求的响应的错误,该请求不包含值为“true”的访问控制允许凭据“头”。我通过添加以下内容解决了这个错误:

CORS_ALLOW_CREDENTIALS = True 

(从django cors headers django应用程序中,将此设置为设置.py)https://github.com/ottoyiu/django-cors-headers

然后手动将标题添加到我的响应中:

response['Access-Control-Allow-Credentials'] = 'true'

我以前已经研究过CORS的部分内容,但是我再次阅读了下面的页面。它似乎没有给出答案。在

https://www.html5rocks.com/en/tutorials/cors/

axios代码:

checkoutCart: function(submittedValues, products) {

  console.log("checkoutCart")

  console.log(submittedValues)

  console.log(products)

  // let data = {

  //   formData: submittedValues,

  //   productData: products,

  // }

  return axios({

    method: 'post',

    url: 'http://127.0.0.1:8000/order/create',

    data: {

      formData: submittedValues,

      productData: products,

    },

    headers: {'Content-Type': 'application/json'},

    //withCredentials: true,

  })

    .then(function(response) {

      console.log(response)

    })

    .catch(function(error) {

      console.log("error", error)

    })

}

Django观点:

from django.views.decorators.csrf import csrf_exempt

from django.http import JsonResponse



@csrf_exempt

def handle_order(request):

    if request.method == 'POST':

        print("request.POST:")

        print(request.POST)

    response = JsonResponse({})

    response['Access-Control-Allow-Credentials'] = 'true'

    return response

Tags: 数据django代码logtrueresponserequestcreate
1条回答
网友
1楼 · 发布于 2024-10-01 00:26:19

使用post可以获取数据:

request.body

获取post数据后,需要用

request.body.decode('utf-8')

如果您希望解析此数据dict,可以使用json库将字符串转换为iterable dict,方法是:

json.loads(your_post_data)

整个代码片段:

def handle_order(request):
    if request.method == 'POST':
        unparsed_json = request.body.decode('utf-8') #Get the data and decode it
        postData = loads(unparsed_json) #Convert it to [dict]
        for keys in postData:
            print(keys) #print all the values in the dict

相关问题 更多 >