首页 > 解决方案 > 将数据附加到 node.js 中的 formData ...我发布到我的 api 的数据总是显示为空?

问题描述

最近我试图通过异步进程将大量 HTML 表单值附加到 MongoDB 数据库

这个 const createproperty 是我在数组中获取的 MongoDB 字段

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

.. 这些 id 是我放入数组中的 HTML 表单中的一些 id

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

这个新属性将为我提供 Html 表单中的值,所有值都以数组的形式存储,这个 for 循环工作得很好,完美地给了我所有的表单值

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

这是遵循异步过程的函数

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

}

我 console.logged 来自 createdata 函数的值,它完美地为我提供了值,但它没有将值推送到 mongodb 服务器,当我查看集合时,有一个文档已创建但其中没有数据..

请帮助我哪里做错了,我不知道我哪里做错了..

非常感谢你帮助我!!

标签: javascriptnode.jsapiexpressasynchronous

解决方案


axios期望数据不是 JSON 对象FormData

createProperty这将使用数组中的键将主体构造为 JSON

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

那么您可以直接通过axios

await createData(data)

推荐阅读