【问题标题】:Multer middlware in Node.js returns empty object in req.body and undefined in req.fileNode.js 中的 Multer 中间件在 req.body 中返回空对象,在 req.file 中返回未定义对象
【发布时间】:2021-03-29 19:03:35
【问题描述】:

问题是当我使用 multer 并在 Postman 中发送请求时,req.body 是一个空对象,而 req.file 是未定义的。我已经取消选中邮递员中的内容类型标头。

这是代码:

//Route
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '../uploads/');
    },
    filename: function (req, file, cb) {
        cb(null, new Date().toISOString() + file.originalname);
    }
});

const upload = multer({
    storage,
    limits: {fileSize: 1024 * 1024 * 10}
});

router.post('/test', upload.single('profilePicture'), authController.test);

//Controller

const test = (req, res) => {
    console.log(req.body)
    console.log(req.files)
    res.json({body:req.body, files:req.files})
}

//app.js

app.use(express.json({extended: true, limit: '30mb'}));
app.use(express.urlencoded({extended: true, limit: '30mb'}))
app.use(cookieParser());

app.use('/api/auth', authRoutes);
app.use('/api/product', productRoutes);
app.use('/api/profile', profileRoutes);

编辑:原来,问题出在 Postman 上。我从一个 React 应用程序向 axios 提出了一个请求,一切正常。所以问题是,为什么它在 Postman 中不起作用?是软件中的一些错误还是我们应该更改的一些设置?

【问题讨论】:

  • 如果用var upload = multer({ dest: 'uploads/' })配置,结果一样吗?
  • 是的,同样的事情。问题出在 Postman 上。

标签: node.js express postman multipartform-data multer


【解决方案1】:

问题是 Nodejs 默认使用 Ansynchornus Javascript。您需要使用async-await 方法和try-catch-finally 方法,而不是传统的 JS 编程。

所以你的控制器看起来像 -

//Route
router.post('/test', async (req, res, next)=>
 {
    try{
         await upload.single('profilePicture')
         next()
    } catch(err){
    console.log(err)
    res.send('failed!')
    }, 

authController.test);

//Controller

const test = async (req, res) => {
   try{

       console.log(req.body)
       console.log(req.files)
       res.json({body:req.body, files:req.files})
    } catch(err){
    console.log(err);
    }

}

答案的后期补充。 如果你只是想访问上传的图片,那么你应该使用buffer。

var storage = multer.memoryStorage()
var upload = multer({ storage: storage })

【讨论】:

  • 你好,谢谢你的回复,但它不起作用,同样的结果:{} undefined
  • 您可以尝试将参数“profilePicture”更改为 req.file 之类的变量吗?我在尝试通过 multer upload fn 中的硬编码字符串引用时遇到了类似的问题
  • 另外,您必须module.exports.test = async() 才能使其在您的路线中可用。我猜你会这样做
  • 什么都试过了,结果一样。问题出在 Postman 内部
  • 解决了你在邮递员中的错误后,这个方法有效吗?
猜你喜欢
  • 2022-12-03
  • 2017-01-15
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 2021-06-02
  • 2016-11-20
  • 2020-02-16
相关资源
最近更新 更多