req.file 在使用 multer 上传图片时未定义

req.file is undefined while using multer for image upload

我在使用 multer 上传图片时遇到 req.file 未定义错误。我正在使用 FormData 将我的图像从 react 发送到 nodejs。我几乎查看了 Stack Overflow 的所有解决方案,但我无法解决问题。

我用于发送文件的 React 代码:

const data = new FormData();
    data.append('profile',e.target.files[0]);
    axios.post('/imagefilter', data).then(res=>console.log(res)).catch(err=>console.log(err))

在我接收文件的地方输入标签:

<input type="file" onChange={(e) => { onChange(e) }} />

nodejs 服务器代码:

 const storage = multer.diskStorage({
destination: (req,file,cb) => {
    console.log(req.files);
    cb(null,path.join(__dirname, './uploads'))
},
filename: (req,file,cb) => {
    cb(null,file.originalname);
}

})

post路线:

router.post(`/imagefilter`,upload.single('profile'),(req, res) => { console.log(req.file)})

我无法找出错误,我已经浪费了将近 24 小时来修复这个错误。

我想当你调用 api 时你需要添加 Content-Type": "multipart/form-data in header.

其实我在用

app.use(fileUpload())

在我创建 imagefilter 路由之前,删除 fileUpload() 后问题得到解决