【问题标题】:How to post data as an array object using axios如何使用 axios 将数据作为数组对象发布
【发布时间】:2021-11-15 12:06:25
【问题描述】:

我有一个函数,我正在使用 axios 将数据发布到 nodeJS rest api。我遇到的问题是 axios 添加了一个包含对象的列表,而不仅仅是数组对象。请帮我解决这个问题。

函数接收来自“文档”的关注

{
      _id: '6149290b197615d32c515dab',
      instantMessage: false,
      isComplete: true,
    },
    {
      _id: '614a249636503d7aa9fb138d',
      instantMessage: false,
      isComplete: true,
    },
    {
      _id: '614a2bf5560184026def253a',
      date: '2021-09-21',
      title: 'Not getting erro',
    },
    {
      _id: '614a2c6a560184026def253d',
      date: '2021-09-21',
      title: 'Every thing working',
    }

我的功能如下:

async function SaveAsTemplate(documents) {
  const result = await axios
    .post('http:localhost/templates', {
      documents,
    })
    .catch(function (error) {
      // handle error
      console.warn(error.message);
    });

  return result;
}

在收到查询的 nodeJS 项目中,我是 console.log 数据,我得到以下结果:

documents: [
    {
      _id: '6149290b197615d32c515dab',
      instantMessage: false,
      isComplete: true,
    },
    {
      _id: '614a249636503d7aa9fb138d',
      instantMessage: false,
      isComplete: true,
    },
    {
      _id: '614a2bf5560184026def253a',
      date: '2021-09-21',
      title: 'Not getting erro',
    },
    {
      _id: '614a2c6a560184026def253d',
      date: '2021-09-21',
      title: 'Every thing working',
    }
  ]

我如何使用 axios,它只给我一个没有前面文档的对象。 当我使用 Postman 和其他工具将查询发送到帖子时,我没有这个问题,一切都正确。仅在使用 axios 时出现问题

【问题讨论】:

    标签: javascript node.js reactjs react-native axios


    【解决方案1】:

    你在做

      const result = await axios
        .post('http:localhost/templates', {
          documents,
        })
    

    等同于:

      const result = await axios
        .post('http:localhost/templates', {
          documents: documents,
        })
    

    尝试:

      const result = await axios
        .post('http:localhost/templates', documents)
    

    【讨论】:

      【解决方案2】:
      async function SaveAsTemplate(documents) {
        const result = await axios
          .post('http:localhost/templates', {
             headers: {
               'Content-Type': 'application/json',
             },
            body: documents,
          })
          .catch(function (error) {
            // handle error
            console.warn(error.message);
          });
      
        return result;
      }
      

      或者您可以尝试先将数组更改为对象,然后在正文中分配

      【讨论】:

      • Teddy 我得到的结果与我的代码相同。
      猜你喜欢
      • 2023-03-26
      • 2019-06-18
      • 2021-09-30
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      • 2023-03-15
      • 2021-05-10
      相关资源
      最近更新 更多