在 Linux Debian Bullseye 上,我在埠 8081 上運行 gulp HTML 服務器,在埠 8083 上運行 Django 后端。我正在嘗試使用 JQuery 的 AJAX 功能從靜態頁面發布一個相對較大的 JSON 檔案。在正確設定 django-cors-headers 模塊后,使用MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware" ],CORS_ALLOWED_ORIGINS和CSRF_TRUSTED_ORIGINSsettings.py,我在 views.py 上撰寫了以下 HTML 視圖,@csrf_exempt裝飾器就位,因為我在本地主機上運行所有內容:
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")
我希望我的 Django 視圖能夠使用request.POST["leasing_order"]. 相反,我在嘗試訪問它時遇到錯誤和失敗。
讓我們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
uj5u.com熱心網友回復:
我在用最少的測驗用例重現這個問題后找到了解決方案。要解決這個問題,你必須將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://www.uj5u.com/net/388234.html
上一篇:.net核心mvc正在到達我發布的json控制器,但我無法讀取它。當我使用[FromBody]時,我也收到錯誤代碼415
