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

Can't get POST data from Django (sending it from React)

我花了几个小时来解决这个问题。问题是我无法发送 POST 的正文数据。我从服务器收到 500 错误。

这是我在 React Native 上的 HTTP 请求(我想我可能有错误的 axios 请求)。 http body 可能有问题?

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: {}>

为什么最后两行总是打印None?我来回检查这些语法二十多次。这太令人沮丧了

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

axios默认将请求数据序列化为json。您可以使用 json.loads 对其进行反序列化。

import json
data = json.loads(request.body.decode('utf-8'))

或者,如果您想使用 request.POST,请参阅 [axios 文档] 以了解以 application/x-www-form-urlencoded 格式发送数据的选项。

如果您使用 djangorestframework 构建视图,您应该通过 request.data 而不是 request.POST 访问数据。 DRF 将自动为您解析 json 并让您访问字典,就像您期望 request.POST 拥有的那样。

request.POST 不同,这也适用于其他 http 方法。

http://www.django-rest-framework.org/api-guide/requests/