![](/img/trans.png)
[英]How to send nested object with array of objects including files in FormData?
[英]How to send array of objects with files via formdata
所以我试图通过 axios 将一组对象发送到后端(我正在使用 express.js)。 当我发送没有文件的对象时,我没有问题,但是一旦我尝试用它发送文件,我就遇到了一些问题。 我知道我必须使用 formData 来做到这一点,而且我之前已经这样做了,但是这次我有一个需要发送的多个对象的数组。 所以不知道这次 append 是如何工作的。 这是我的对象的简化版本
const treatementListe = {
"id": 0,
"date": "2021-10-22T09:41:19.678Z",
"selectedTraitements": "Injection1",
"selectedZones": "Face",
"traitementNote": "Careful",
"files": [
{
"upload": {
"uuid": "be68c533-92d5-4f5d-b9e4-ba338f264641",
"progress": 100,
"total": 20261,
"bytesSent": 20261,
"filename": "1617826401810IMG-20210211-WA0002.jpg",
"chunked": false,
"totalChunkCount": 1
},
"status": "success",
"previewElement": {},
"previewTemplate": {},
...etc
}
]
},
{
"id": 1,
"date": "2021-10-22T09:41:19.678Z",
"selectedTraitements": "Injection2",
"selectedZones": "Ear",
"traitementNote": "Careful",
"files": [
{
"upload": {
"uuid": "be68c533-92d5-4f5d-b9e4-ba338f264641",
"progress": 100,
"total": 20261,
"bytesSent": 20261,
"filename": "1617826401810IMG-20210211-WA0002.jpg",
"chunked": false,
"totalChunkCount": 1
},
"status": "success",
"previewElement": {},
"previewTemplate": {},
...etc
}
]
}
axios 发布请求
typeForm() {
const fd = new FormData();
fd.append('traitementsListe', traitementsListe)
//isn't working
console.log(traitementsListe)
if(traitementsListe.length > 0) {
const patient = axios.post(`${baseUrl}addOldfolder`, fd)
.then(response => {
console.log(response)
return response.data;
}).catch(error => ({ error: JSON.stringify(error) }));
}
}
编辑:这是我的后端代码
router.post('/addOldfolder', async(req,res) =>{
try {
console.log(req.body)
// output empty object
res.send(req.body)
// sends empty object
} catch(err){
res.status(400).send(err);
}
})
喜欢下面
fd.append('traitementsListe', JSON.stringify(traitementsListe));
问题解决了。 但我真的不明白为什么它有效,我所要做的就是添加
router.post('/addOldfolder', upload.array("files"), async(req,res) =>{
try {
console.log(req.body)
// output empty object
res.send(req.body)
// sends empty object
} catch(err){
res.status(400).send(err);
}
})
因为我在上传文件时多次使用该中间件。 我设法通过添加中间来控制对象!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.