[英]Can't get POST data from Django (sending it from React)
我要花幾個小時來解決這個問題。 問題是我無法發送POST的正文數據。 我從服務器收到500錯誤。
這是我在React Native上的HTTP請求(我認為我可能有錯誤的axios請求)。 http正文上可能有問題?
export const createCloth = (token, hType, clothObject) => async dispatch => {
let headers = { 'Authorization': `JWT ${token}`};
if(hType==1) {
headers = { 'Authorization': `JWT ${token}`};
} else if (hType==2) {
headers = { 'Authorization': `Bearer ${token}`};
}
let {image, text, clothType, ... , onlyMe} = clothObject;
console.log(text); <- printing ok
console.log(bigType); <- printing ok
let response = await axios.post(`${ROOT_URL}/clothes/create/`, {
text, clothType, ..., onlyMe
}, {headers});
console.log(response.data); <<< 500 HTTP error
這是我后端API的一部分。
class ClothCreateAPIView(APIView):
def post(self, request, format=None):
# Create Cloth
# self.request.POST.get('user_id')
print('--------REQUEST-------')
print(request)
logged_in_user = self.request.user
content = self.request.POST.get('text')
cloth_type = self.request.POST.get('clothType')
only_me = self.request.POST.get('onlyMe')
...
print('----------PRINTING CLOTH CONTENT')
print(logged_in_user) <- printing my username (GOOD)
print(cloth_type) <- printing None always (BAD)
print(content) <- printing None always (BAD)
print(self.request.POST) <- prints <QueryDict: {}>
在最后兩行,為什么他們總是不打印? 我來回檢查這些語法超過二十次。 真令人沮喪
self.request.POST.get('somthing')語法沒什么問題,但是它不起作用的原因是我們對axios請求的語法有疑問
默認情況下,axios將請求數據序列化為json。 您可以使用json.loads
反序列化它。
import json
data = json.loads(request.body.decode('utf-8'))
或者,如果要使用request.POST
,請參閱[axios docs]以獲取以application/x-www-form-urlencoded
格式發送數據的選項。
如果使用djangorestframework構建視圖,則應通過request.data
而不是request.POST
訪問數據。 DRF將自動為您解析json,並讓您訪問字典,就像您期望request.POST
具有的那樣。
這也適用於其他http方法,與request.POST
不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.