Home > Blockchain >  How to post data as an array object using axios
How to post data as an array object using axios

Time:09-22

I have a function that I am using axios to post data to nodeJS rest api. The problem that I am having is that axios added post a list with the object instead of just the array object. Please help me fix this.

The function receives the follow from "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',
    }

my function is as follow:

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

  return result;
}

in my nodeJS project where the query is received I am console.log the data and I am getting the follow results:

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',
    }
  ]

How can I use axios where it only give me the object without documents in front. When I use Postman and other tools to send query to post I do not have this problem everything come out correct. Only have issues when using axios

CodePudding user response:

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;
}

or you can try to change array to object first and then you assign on body post

CodePudding user response:

You're doing

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

which is the same as:

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

try:

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