python - Django(DRF)未显示 CORS POST 数据(来自 React 前端)
问题描述
我正在使用 React 前端,与 DRF(Django Rest Framework)后端进行通信。
目前两者都在自己的开发服务器上运行,因此它们在不同的域上运行。
我正在使用 POST 方法从前端向后端发送数据,使用 Axios 发送请求。
我使用的代码如下所示。
问题:
Django 似乎没有收到 POST 数据。
正如您在下面的代码中看到的,我尝试打印出接收到的数据,但这是我在控制台中看到的:
[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 请求的行。即使打印语句是由 POST 请求执行的,而不是由 OPTIONS 请求执行的。这最初让我有点困惑.)
我已经尝试过的:
我尝试添加以下标题:
headers: {'Content-Type': 'application/json'}
我试过添加:
withCredentials: true
(在我的代码中注释掉,如果这篇文章在底部)
最初,这给了我一个关于对预检请求的响应的错误,该响应不包含值为“true”的 Access-Control-Allow-Credentials 标头。我通过添加以下内容解决了这个错误:
CORS_ALLOW_CREDENTIALS = True
(来自 django-cors-headers Django 应用程序,在 settings.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
解决方案
您可以使用以下方法获取帖子数据:
request.body
获取帖子数据后,您需要对其进行解码
request.body.decode('utf-8')
如果你想解析这个数据字典,你可以使用json
库将字符串转换为可迭代的字典,方法是:
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
推荐阅读
- javascript - 如何使用闪亮的 JS 单击绘图模式栏按钮?
- html - 每个框的绘图框和宽度被忽略,一般间距不起作用
- c# - 通过反射访问受保护字段时的 FieldAccessException
- javascript - 如何使用 DrawerNavigation 导出一个类并将其导入 React-native 的另一个类中?
- django - 如何使用具有来自不同查询集的值的 Modelchoice 字段创建 Django 表单/表单集
- r - 是否可以通过某些规则重新排序 R tibble 的列?
- windows-ce - 将.net项目4.5框架转换为支持2008年开发的windowsCE(smartDevice)项目
- xml - 获取嵌套 XML 模式的数据框
- c++ - 如何在arduino中制作另一个类库的实例变量
- algorithm - 线性回归的梯度下降未找到最佳参数