【问题标题】:Request body is empty when submitting data using "form data"使用“表单数据”提交数据时请求正文为空
【发布时间】:2020-05-11 00:38:54
【问题描述】:

当我使用原始 JSON 更新时,它可以工作,但是当我使用表单数据时,它不会更新。使用表单数据时的请求正文是一个空对象。为什么会这样?

这是我的更新代码:

exports.updateProgram = catchAsync(async (req, res, next) => {
    console.log('req ko body',req.body)
    let doc = await Program.findByIdAndUpdate(req.params.id, req.body, { runValidators: true, new: true })
    if (!doc) {
        return next(new AppError('No document found with that ID', 404))
    }
    res.status(200).json({
        status: 'success!',
        data: { doc }
    })
})

在邮递员中:

我正在使用 multer,实际上我在 req.body 中传递了照片。代码如下:

let multerStorage = multer.memoryStorage()

let multerFilter = (req, file, cb) => {
    if (file.mimetype.split('/')[0] == 'image') {
        cb(null, true)
    } else {
        cb(new AppError('Not an image!', 400), false)
    }
}

let upload = multer({
    storage: multerStorage,
    fileFilter: multerFilter
})

exports.uploadPhotos =  upload.fields([
    { name: 'abcd', maxCount: 10 },
    { name: 'photos', maxCount: 10 },
    {name: 'photos3', maxCount: 10}
])

exports.resizePhotos = catchAsync(async (req, res, next) => {
    // if (!req.files.photos || !req.files.abcd) return next()
    if(req.files.abcd) {
    req.body.abcd = []
   await Promise.all(req.files.abcd.map(async (file, i) => {
       let filename = `tour-${Date.now()}-${i + 1}.jpeg`
       await sharp(file.buffer)
       .resize(500,500)
       .toFormat('jpeg')
       .jpeg({ quality: 90 })
       .toFile(`public/img/arpit/${filename}`)
       req.body.abcd.push(filename)
   }) 
   )} else if(req.files.photos3) {
    req.body.photos3 = []
    await Promise.all(req.files.photos3.map(async (file, i) => {
        let filename = `tour-${Date.now()}-${i + 1}.jpeg`
        await sharp(file.buffer)
        .resize(500,500)
        .toFormat('jpeg')
        .jpeg({ quality: 90 })
        .toFile(`public/img/arpit/${filename}`)
        req.body.photos3.push(filename)
    }) 
    )}
   else if(req.files.photos) {
    // console.log('codee here')
    // } else if(req.body.photos) {
     req.body.photos = []
     console.log('req.files>>>', req.files)
    await Promise.all(req.files.photos.map(async (file, i) => {
        let filename = `tour-${Date.now()}-${i + 1}.jpeg`
        await sharp(file.buffer)
        .resize(500,500)
        .toFormat('jpeg')
        .jpeg({ quality: 90 })
        .toFile(`public/img/programs/${filename}`)
        req.body.photos.push(filename)
    })
    )
}
    return next()
})

我正在导入路由文件

【问题讨论】:

  • 您能告诉我们您是如何发送此表单数据的吗?
  • @EnriqueBermúdez 检查编辑后的帖子

标签: express postman


【解决方案1】:

Express (bodyParser) 无法处理多部分表单数据,这就是您的代码无法正常工作的原因。

看看multer,一个快递包裹。它是一个提供您正在寻找的功能的中间件。

【讨论】:

  • 你在哪里导入updateProgram函数?我可以看到那部分吗?
  • 这两条路由我看不到multer中间件的使用情况。
【解决方案2】:
var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }]);
app.post('/cool-profile', cpUpload, function (req, res, next) {


    // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
      //
      // e.g.
      //  req.files['avatar'][0] -> File
      //  req.files['gallery'] -> Array
      //
      // req.body will contain the text fields, if there were any

})

这可能会对您有所帮助。引用自https://www.npmjs.com/package/multer#readme

【讨论】:

    猜你喜欢
    • 2021-08-12
    • 2021-02-22
    • 2019-10-22
    • 2022-01-11
    • 2020-10-09
    • 1970-01-01
    • 2014-12-24
    • 2021-10-15
    • 2021-12-01
    相关资源
    最近更新 更多