【发布时间】:2021-03-25 20:48:57
【问题描述】:
我正在尝试使用我的自定义 API(Node JavaScript)上传一组图像,在这里我只想将文件名保存到我的数据库中,并且文件的上传工作正常(我为上传创建的中间件工作得很好,因为我尝试在 postman 中使用相同的中间件)。
当涉及到实际的 JavaScript 文件时,它不起作用并显示以下错误:
值“{'0':{},'1':{}}”在路径“images”处转换为字符串失败,图像:值“[ {'0':{},转换为数组失败, '1': {} } ]" 在路径“图像”
这是我的代码
const createProperty = ['city', 'propertyType', 'propertyName', 'images'];
const newProperty = new Array();
for (var i = 0; i < myids.length; i++) {
newProperty[i] = $(myids[i]).val();
}
newProperty[myids.length] = [document.getElementById('PropertyPhotos').files];
const data = {};
createProperty.forEach((id, index) => {
data[createProperty[index]] = newProperty[index]
})
await createData(data);
// here is the CreateDate function
export const createData = async (data) => {
try {
const res = await axios({
method: 'POST',
url: '/api/v1/properties',
data
});
if (res.data.status === 'success') {
showAlert('success', 'Property Created Successfully');
}
console.log(res.data);
} catch (err) {
showAlert('error', err.response.data.message);
console.log(err.response.data.message);
}
}
【问题讨论】:
-
我认为您应该使用 JSON.stringify 将对象转换为字符串。
-
newProperty 和 document.getElementById('PropertyPhotos').files 的值是多少?您想插入/复制图像文件并从中获取二维数组吗?请使用控制台日志或调试器来确定问题出现的位置并发布代码的预期行为
-
迭代时myids中有什么?请在您的代码中显示。
标签: javascript node.js arrays asynchronous fetch-api