[英]Body in Request ignored when forming POST dict in Django
我正在使用從 POST 數據中獲取整數的 Django 服務器。 如果我通過 GET 發送整數沒有問題,但是通過 POST 發送時它會被丟棄。
我運行服務器:
./manage.py runserver 0.0.0.0:8000
然后使用以下命令生成 POST 請求:
curl -X POST -H "Content-Type: application/json" -d '{"myInt":4}' "http://0.0.0.0:8000/myURL/"
我在視圖中使用 PDB,這是我為以下命令獲得的結果:
request.method
> 'POST'
request.body
> '{"myInt":4}'
request.POST
> <QueryDict: {}>
我使用 @csrf_exempt 作為視圖的裝飾器,只是為了確保它不會引起任何問題。
目前令我感到困惑的是 request.POST 不包含 myInt,我的 POST 請求格式不正確嗎?
您的帖子請求發送的是 JSON 而不是 application/x-www-form-urlencoded
如果您查看有關 HttpRequest.POST的Django 文檔。
A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data. See the QueryDict documentation below. If you need to access raw or non-form data posted in the request, access this through the HttpRequest.body attribute instead.
您需要 POST 表單編碼數據。 我沒有對此進行測試,也有一段時間沒有使用 curl,但我相信以下內容應該有效。
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "myInt=4" "http://0.0.0.0:8000/myURL/"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.