无法读取“未定义”的属性“缓冲区”

时间:2019-04-02 11:01:29

标签: node.js mongodb file mongoose buffer

我正在构建一个应用程序,其中要填写一个也有文件的表格。我从“ req.file”中获取文件,并从“ req.body”中获取其他内容。 “文件”不是“必需”。用户可以附加或不能附加。当用户附加文件时,一切顺利,但是当用户未附加文件时,我发现此错误。 can not read property "buffer" of undefined.。我已将猫鼬模式类型设置为“图像”为“缓冲区”。这是我从“ 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,

1 个答案:

答案 0 :(得分:1)

假设要先创建对象,然后再将其添加到数据库,则需要首先检查const XLSX = require('xlsx'); const { CONTACT } = require('./column.config'); const _ = require('lodash'); const uploadExcel = (req, res, next) => { try{ const columnMapper = CONTACT; const workbook = XLSX.read(req.file.buffer, {type:'buffer'}); const sheetName = workbook.SheetNames; const excelJson = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName[0]]); if(!excelJson.length) { throw Error("Blank sheet"); } const columnCheck = Object.keys(excelJson[0]); const isColumnEqual = _.isEqual(columnMapper, columnCheck); if(!isColumnEqual){ throw Error("Blank sheet"); } next(); } catch(e){ console.log(e) return res.status(400).send({error:e.message}); } } module.exports = uploadExcel; 是否为空。

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 } ,不会引发错误。