javascript - 将数据附加到 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 服务器,当我查看集合时,有一个文档已创建但其中没有数据..
请帮助我哪里做错了,我不知道我哪里做错了..
非常感谢你帮助我!!
解决方案
axios期望数据不是 JSON 对象FormData
createProperty
这将使用数组中的键将主体构造为 JSON
const data = {};
myids.forEach((id, index) => {
data[createProperty[index]] = $(myids[i]).val();
})
那么您可以直接通过axios
await createData(data)
推荐阅读
- blockchain - 使用 @Solana\web3.js 传输 SPL 令牌
- swift - 后台线程是否仅在应用程序在 IOS swift 中处于顶部时才起作用?
- python - 如何在python中的函数内编译/组合多行代码?
- java - Spring引导Elasticsearch得到ClassNotFoundException:org.elasticsearch.client.RequestOptions
- python - 如何使这个循环并行且更快?
- java - 无法从外部 PC 连接到在 Docker 容器中运行的 Java 应用程序 - Linux
- linux - 权限被拒绝(公钥、密码)。rsync:连接意外关闭 - gitlab
- python - 在 Dockerfile 中没有 root 用户的 pip wheel install 引发权限错误
- vue.js - 无法在 vue ui 中创建或导入项目
- c++ - 稀疏矩阵的子矩阵