You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MERN栈Multer文件上传异常:req.body为空、req.file为undefined

解决MERN栈中Multer文件上传req.file/req.body为空的问题

我来帮你排查几个关键问题,这些应该就是导致你上传失败的核心原因:

1. 后端路由配置写法错误

你当前的路由代码存在语法问题:

router.route('/upload',upload.single('mfile')).post(addImage)

router.route()方法仅接收路径参数,不能直接将multer中间件作为第二个参数传入。正确的写法应该把multer中间件放在post方法的参数列表中,有两种可选写法:

// 写法一:直接使用post方法定义路由
router.post('/upload', upload.single('mfile'), addImage);

// 写法二:使用route链式调用
router.route('/upload')
  .post(upload.single('mfile'), addImage);

2. 前端Axios请求传参格式错误

你现在把FormData包裹在了一个普通对象里发送:

const addedValue={ formData }
addImage(addedValue)

这种做法会让Axios默认以application/json格式发送请求,而Multer只负责解析multipart/form-data类型的请求,自然无法识别到文件。你需要直接传递FormData对象:

// 修改前端handleSubmit逻辑
const handleSubmit=(e)=>{
 e.preventDefault()
 const formData = new FormData()
 // 注意:这里的key要和后端multer配置的字段名一致!
 formData.set('mfile', file[0])
 // 直接传formData,不要包裹成对象
 addImage(formData)
 setfile('')
}

// 同步修改addImage请求函数
function addImage(formData){
 // Axios会自动识别FormData并设置正确的Content-Type请求头
 axios.post('http://localhost:4000/blog/upload', formData).then(res=>{
 dispatch({ type:'ADD_IMAGE', payload:res.data })
 }).catch(error=>{
 console.log(error)
 })
}

这里要特别注意:前端FormData设置的key必须和后端upload.single('xxx')中的xxx完全一致,你之前前端用了file,后端用了mfile,这会导致Multer找不到对应字段,一定要统一。

3. 额外说明:body-parser不处理multipart/form-data

你项目中使用的body-parser.json()和body-parser.urlencoded()中间件,仅负责解析application/json和application/x-www-form-urlencoded格式的请求,不会处理multipart/form-data类型的请求。不过你当前的中间件加载顺序没问题,Multer会自行处理该类型请求,这部分无需修改。

验证修改效果

完成上述调整后重新测试:

  • 前端选择文件提交后,后端控制台应该能打印出req.file的详细信息,不再是undefined;如果后续你在表单中添加其他文本字段,req.body也会正确解析对应内容。

内容的提问来源于stack exchange,提问作者october cms

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 14:53:13