Skip to content
Advertisement

Appended data to formData in node.js…the data which i am posting to my api is always showing null?

Recently I was trying to append a lot of HTML form values to MongoDB database through an async process

this const createproperty are my MongoDB fields which i have taken in an array

 const createProperty =  ['propertyType',
                      'propertyName',
                      'bhkType',
                      'ownershipType',
                      'builtUpArea',
                      'propertyAge',
                      'floorType',
                      'floorNumber',
                      'numberOfFloors',
                      'city',
                      'expectedPrice',
                  ]

.. these ids are some id’s from the HTML form which i have put in an array

const myids = ['#thisPropertyType',
            '#thisPropertyName',
            '#thisBhk',
            '#thisOwnerShip',
            "#thisArea",
            '#thisAge',
            '#thisFloor',
            '#thisFloorNo',
            '#thisTotalFloor',
            '#thisCity',
            '#thisEp', ] 

this newproperty will give me the values from the Html form, all of the values are stored in the form of an array and this for loop works just fine which gives me all the form values perfectly

const newProperty = new Array();
    for(var i=0;i<myids.length;i++){
        newProperty[i] = $(myids[i]).val();
    }

             const form = new FormData();
            for(var i=0;i<newProperty.length;i++){
                form.append(createProperty[i],newProperty[i]);
            }
            await createData(form);

this is the function which follows the async process

       export const createData = async (data) => {
try{
    for (var value of data.values()) {
        console.log(value); 
     }
    const res = await axios({
        method: 'POST',
        url: '/api/v1/myapi',
        data
    });

    if(res.data.status==='success'){
       alert('success');
    }
    console.log(data);
}
catch(err){
    alert('error');
}

}

i console.logged the values from the createdata function, it gives me the values perfectly but it is not pushing the values to the mongodb server, when i look at the collection, there is an document which is created but it has no data in it..

please help me where have i done wrong, i’m not getting where did i go wrong..

Thank you so much for helping me out!!

Advertisement

Answer

axios expect the data to be JSON object not FormData

This will construct the body as JSON with keys from createProperty array

const data = {};
myids.forEach((id, index) => {
    data[createProperty[index]] = $(myids[i]).val();
})

then you can send these values directly through axios

await createData(data)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement