在上,我在端口8081上运行一个gulp服务器,在端口8083上运行一个Django后端。我试图使用JQuery的AJAX特性从静态页面发布一个相对较大的JSON文档。在正确地设置了django-cors-headers模块之后,使用MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware" ]、CORS_ALLOWED_ORIGINS和CSRF_TRUSTED_ORIGINS对settings.py进行了编码,在views.py上编写了下面的HTML视图,使用@csrf_exempt装饰器,因为我在localhost上运行所有内容:
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def processOrder(request):
leasing_order_unicode = request.body.decode("utf-8")
print(request.POST.__dict__)
print(request.POST["leasing_order"])
return HttpResponse(leasing_order_unicode, headers={ "Access-Control-Allow-Origin": "http://localhost:8081", "Content-Type": "application/json" })然后我将它添加到urls.py中,如下所示:
path("processorder", processOrder, name="processorder"),我希望JSON视图能够使用request.POST["leasing_order"]访问JSON。相反,在尝试访问时,会遇到错误和失败。
让serializedata()是一个函数,负责将所有本地数据收集到一个对象中,然后序列化它。如果我使用multipart/form-data编码发布表单数据,如下所示:
export function sendOrder_multipart()
{
let finalorder = serializedata();
let finalorder_postdata = new FormData();
finalorder_postdata.append("leasing_order", finalorder);
$.ajax({ method: "POST", url: "http://localhost:8083/orderstable/processorder",
data: finalorder_postdata, processData: false, contentType: "multipart/form-data" });
}在Django后端的控制台输出中,我得到了以下错误:
Bad request (Unable to parse request body): /orderstable/processorder
Traceback (most recent call last):
File "<project path>/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "<project path>/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "<project path>/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "<project path>/<website>/orderstable/views.py", line 54, in processOrder
print(request.POST.__dict__)
File "<project path>/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 102, in _get_post
self._load_post_and_files()
File "<project path>/lib/python3.9/site-packages/django/http/request.py", line 328, in _load_post_and_files
self._post, self._files = self.parse_file_upload(self.META, data)
File "<project path>/lib/python3.9/site-packages/django/http/request.py", line 287, in parse_file_upload
parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
File "<project path>/lib/python3.9/site-packages/django/http/multipartparser.py", line 76, in __init__
raise MultiPartParserError('Invalid boundary in multipart: %s' % force_str(boundary))
django.http.multipartparser.MultiPartParserError: Invalid boundary in multipart: None
[17/Dec/2021 20:29:11] "POST /orderstable/processorder HTTP/1.1" 400 143如果我将Javascript前端的函数调整为不使用multipart/form-data编码,如下所示:
function sendOrder_nomultipart()
{
let finalorder = serializedata();
let finalorder_postdata = new FormData();
finalorder_postdata.append("leasing_order", finalorder);
$.ajax({ method: "POST", url: "http://localhost:8083/orderstable/processorder",
data: finalorder_postdata, processData: false });
}我得到的结果略有不同,但仍然无法通过request.POST访问我的字符串
{'_encoding': 'UTF-8', '_mutable': False}
Internal Server Error: /orderstable/processorder
Traceback (most recent call last):
File "<project root>/lib/python3.9/site-packages/django/utils/datastructures.py", line 83, in __getitem__
list_ = super().__getitem__(key)
KeyError: 'leasing_order'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<project root>/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "<project root>/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "<project root>/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "<project root>/<website>/orderstable/views.py", line 55, in processOrder
print(request.POST["leasing_order"])
File "<project root>/lib/python3.9/site-packages/django/utils/datastructures.py", line 85, in __getitem__
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'leasing_order'
[17/Dec/2021 20:35:59] "POST /orderstable/processorder HTTP/1.1" 500 106954发布于 2021-12-20 20:38:57
--我在用最小测试用例再现这个问题后找到了解决方案。要解决此问题,必须将POST数据作为简单对象传递到$.ajax(),而不是使用FormData()对象,并省略配置对象的contentType和processData字段。
有效的代码:
function sendOrder_thegoodone()
{
let finalorder = serializedata();
let finalorder_obj = { leasing_order: finalorder };
$.ajax(
{
method: "POST",
url: "http://localhost:8083/orderstable/processorder",
data: finalorder_obj
});
}https://stackoverflow.com/questions/70400707
复制相似问题