无法从Django获取POST数据(从React发送)

hel*_*eer 1 javascript django django-views django-rest-framework axios

我花了几个小时来解决这个问题.问题是我无法发送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
Run Code Online (Sandbox Code Playgroud)

这是我的Backend 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: {}>
Run Code Online (Sandbox Code Playgroud)

在最后两行,他们为什么总是打印无?我来回检查这些语法超过二十次.这太令人沮丧了

self.request.POST.get('somthing')语法没有错,但是它不起作用的原因是我们在axios请求的语法上有问题

Ala*_*air 10

默认情况下,axios将请求数据序列化为json.您可以使用json.loads它反序列化它.

import json
data = json.loads(request.body.decode('utf-8'))
Run Code Online (Sandbox Code Playgroud)

或者,如果要使用request.POST,请参阅[axios docs]以获取以application/x-www-form-urlencoded格式发送数据的选项.