首页 > 解决方案 > DRF 在使用 Axios 发布的 JSON 对象中获取空数组

问题描述

我正在尝试将数据从 Axios 发布到 Django Rest Framework API 端点。

我的数据包含嵌套对象,如下所示:

{
  'name': 'foo',
  'index': 1,
  'nested': [
     { 
       'some_key': 'some_value,
       'geojson_data': { ... }
     },
  ]
}

编辑nested属性包含内部带有geojson数据的对象数组(由解析.geojson文件产生),所以它很深。

我的 axios 函数在这里定义:

async post(data) {
    return axios
      .post(API_URL + 'endpoint/', 
      data,
      {
        headers: authHeader()
      })
      .then(response => {
        return response.data;
      })
  }

authHeader()用于提供 Bearer 令牌授权。

我检查传递给 axios 的数据是否正确。在我的 DRF 视图中,我处理发布请求以处理嵌套输入数据(一对多关系)。

def post(self, request, format=None):
    print(request.data) #empty nested array
    # Do something with my data

如果我 print request.datanested数组是空的,但其他属性不是。看起来像 :

{
  'name': 'foo',
  'index': 1,
  'nested': []
}

我尝试使用 pytest 测试我的 API,并且我的测试通过了类似的数据。那么为什么嵌套对象没有被处理呢?这是我的 axios 调用的问题吗?

我已经读过 axios 可以发送 Json 对象而不需要对其进行字符串化,并且 DRF 也可以从中获取 JSON 数据,request.data那么我错在哪里?

我还尝试添加application/json到 headers 的 content-typ 属性,但没有成功。

标签: django-rest-frameworkaxios

解决方案


推荐阅读