req.files return 未定义的数据,而 req.body 已填充

req.files return undefined data while req.body is populated

设置:

症状:

当通过 http POST 调用发送字符串化 JSON 数据和图像的混合时,服务器通过 multer(multer.any()) 接收随机数量的图像。文件已上传并存在于服务器的 public 文件夹中。 req.body 也可以,但不知何故我无法访问 req.files。它 returns undefined。从 heroku 和我的桌面本地主机,应用程序运行良好。图片上传成功,访问req.files数据也没有问题。只有 VPS/CentOS7 服务器有问题。

客户端(React / Superagent / Babel / Webpack)

import request from 'superagent'

request.post('/modwimg')
.query({
  //some token and other info goes here
})
.accept('application/json')
.field('data',JSON.stringify(jsonData))
.attach('image',this.state.imagedata)
.attach('bannerimage',this.state.bannerimagedata)
.then((res)=>{
  console.log('upload finished')
  this.setState({goback:true})
})
.catch((err)=>{

})

服务器端

const bodyParser = require('body-parser')
const multer = require('multer')
const pubDir = path.join(__dirname, 'pub')
const storage = multer.diskStorage({
  destination: (req,file,cb)=>{
    cb(null,'pub/')
  },
  filename: (req,file,cb)=>{
    cb(null,Date.now() + file.originalname)
  }
})
const upload = multer({storage:storage})

//allowing public access, image goes to public dir
app.use('/pub', express.static(pubDir))

/* initialize bodyparser to build up RESTful app */
//file size limit expansion
app.use(bodyParser.urlencoded({limit:'50mb', extended:true}))
app.use(bodyParser.json({limit:'50mb'}))

app.post('/imageupload',upload.any(),(req,res,next)=>{
  //some token approval goes here
  console.log(req.files) // <----this returns undefined data, but image is still uploaded
  console.log(req.body) // <---- this is fine!!

  //putting data(JSON.parse(req.body)) to db
  db.any( //....
  )
  //then respond to client
  res.json({result:true})
})

问题已解决。我已将 extended 选项从 app.use(bodyParser.urlencoded({limit:'50mb', extended:true})) 更改为 extended:false,现在它就像变魔术一样有效。我从某处读到 bodyParserextended 选项将其余的 http 请求数据转换为其他格式,所以我更改了它,现在可以使用了。