无法读取 "undefined" 的 属性 "Buffer"

Can not read property "Buffer" of "undefined"

我正在构建一个应用程序,我正在其中填写一个也有文件的表格。我从 "req.file" 获取文件,从 "req.body" 获取其他内容。 "file" 不是 "required"。用户可以附加或不能附加。当用户附加时,一切顺利,但是当用户不附加文件时,我发现了这个错误。 can not read property "buffer" of undefined.。我已将 "image" 的猫鼬模式类型设置为 "Buffer"。这是我从 "req".

获取文件和其他数据时的代码
image: req.file.buffer,

geolocation: req.body.geolocation,

details: req.body.details,

location: req.body.location,

status: req.body.status,

spam: req.body.spam,

假设您在将对象添加到数据库之前创建对象,您需要首先检查 req.file 是否为空。

{
 image: req.file.buffer ?  req.file.buffer :  null; 
 geolocation: req.body.geolocation,
 details: req.body.details,
 location: req.body.location,
 status: req.body.status,
 spam: req.body.spam
}


因此,如果您的表单没有 req.file.buffer,它不会抛出错误。