从前端进行 Axios 调用时,后端未收到 req.formData

问题描述 投票:0回答:1

前端调用axios后,后端没有收到

req.formData
。它显示 MERN 应用程序中未定义的值。

前端代码:

const handleDp = async(e)=\>{
e.preventDefault()
const file = fileRef.current.files\[0\]
console.log(file)
console.log('11');
let formData = new FormData();
console.log(formData);
formData.append("image",file, file?.name)
await axios.patch('http://localhost:3000/update',{
withCredentials:true,  
formData:formData,
headers: {
'x-access-token': localStorage.getItem('token'),
'Content-Type': 'multipart/form-data'
},

    })
    .then(res => {
        if (res.data.success) {
            console.log("profile updated");
            window.location.reload();
        }

})
}

后端路由:

router.patch('/update', userMiddleware.upload.single('image'),updateProfile)

后端控制器:

const updateProfile = async(req,res,next)=\>{
console.log(formData)
const file = req.file
console.log(file)
const data = req.formData
console.log(data);
if(!req.file){
return res.json({error: 'Image is required'})
}
const path = data.path.slice(7)
const filepath = `http://localhost:3000/${path}`
try {
await User.findOneAndUpdate({\_id: req.id}, {$set:{image:filepath}})
console.log("file updated");
res.json({success: true, url:filepath})
} catch (error) {
console.log(error)
}
}
node.js reactjs axios multipartform-data form-data
1个回答
0
投票

formData
必须是 axios 的第二个参数,而不是在选项对象中。

例如,

const res = await axios.patch('http://localhost:3000/update', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
});

尝试与上面类似的东西。

© www.soinside.com 2019 - 2024. All rights reserved.