所以我试图通过axios发送一个对象数组到后端(我使用express.js)。当我发送没有文件的对象时,我没有问题,但是当我试图用它发送文件时,我遇到了一些问题。我知道我必须使用formData来做到这一点,我之前已经这样做了,但这次我有一个数组的多个对象,我需要发送。所以不知道这次追加是如何工作的。这是我的对象
的简化版本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 post request
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);
}
})
do like bellow
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);
}
})
因为我在上传文件时多次使用了那个中间件。我设法通过添加中间来安慰对象!