【问题标题】:Nodejs Cannot read property 'filename' of undefinedNodejs无法读取未定义的属性“文件名”
【发布时间】:2021-03-05 08:24:10
【问题描述】:

我对 nodejs 有问题, 当我想用图片发帖时,我收到一条错误消息“无法读取未定义的属性'文件名'”

我看不到我的错误在哪里,请您赐教

这是我的中间件 multer:

const multer = require('multer');

const MIME_TYPES = {
  'image/jpg': 'jpg',
  'image/jpeg': 'jpg',
  'image/png': 'png',
  'image/gif': 'gif',
  
};

const storage = multer.diskStorage({
  destination: (req, file, callback) => {
    callback(null, 'images');
  },
  filename: (req, file, callback) => {  
    const name = file.originalname.split(' ').join('_');
    const extension = MIME_TYPES[file.mimetype];
    callback(null, name + Date.now() + '.' + extension);
  }
});


module.exports = multer({storage: storage}).single('image');

在我的 app.js 中

app.use('/images', express.static(path.join(__dirname, 'images')));

在我的 post.routes.js 中

const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const multer = require('../middleware/multer-config')
const postCtrl = require('../controllers/postController');

router.post('/new', auth, multer, postCtrl.createPost);

在我的 postController.js 中

exports.createPost = (req, res) => {
    
    // Create post in database
    console.log(req.body)
    const article = {
        title: req.body.title,
        content: req.body.content,
        userId: req.body.userId,
        picture: `${req.protocol}://${req.get('host')}/images/${req.file.filename}`
    };
    Post.create(article)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while creating the Article."
      });
    });
}; 

【问题讨论】:

  • 该属性的使用位置... req.file.filename
  • 这里 : 文件名: (req, file, callback) => { const name = file.originalname.split(' ').join('_');常量扩展 = MIME_TYPES[file.mimetype];回调(空,名称 + Date.now() + '.' + 扩展名); } });

标签: javascript node.js express multer


【解决方案1】:

我想问题就在这里

picture: `${req.protocol}://${req.get('host')}/images/${req.file.filename}`

可能是您的请求没有属性“文件”, 如果你在body中发送id,它必须是这样的——req.body.file.filename

最好检查您的请求。

【讨论】:

  • 我尝试 ${req.protocol}://${req.get('host')}/images/${req.body.file.filename} 不工作
  • 你能在这里写下你的请求正文吗?
【解决方案2】:

在控制器中尝试控制台记录 req.file。如果未定义,则有两种概率

  1. 请求中未发送图像
  2. multer 不存储它

如果它没有被存储,我确实遇到了同样的问题,用 Date.now() 创建文件名不起作用,你可以试试这个

name + '-' + Math.random().toString().slice(2, 6) + '-' + Math.random().toString().slice(2, 6) + extension

【讨论】:

  • 我尝试了一个 console.log(req.file) 它是未定义的,并且没有发送图像
【解决方案3】:

就我而言:

.babelrc 中删除 "transform-react-jsx-source" 解决了这个问题。

这是我的 .babelrc 文件在删除 "transform-react-jsx-source" 后的样子:

{
  "presets": ["babel-preset-expo"],
  "env": {
    "development": {
      "plugins": []
    },
    "production": {
      "plugins": ["transform-remove-console"]
    }
  }
}

【讨论】:

    猜你喜欢
    • 2022-12-07
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    • 2017-03-06
    • 2021-12-23
    • 1970-01-01
    相关资源
    最近更新 更多