首页 > 解决方案 > 当我尝试在没有图像的情况下保存时,它显示以下错误““消息”:“无法读取未定义的属性'路径'”。?

问题描述

当我尝试在没有图像的情况下保存时,它显示以下错误““消息”:“无法读取未定义的属性'路径'”。?

    // product controller
  exports.products_create_product = (req, res, next) => {
  const product = new Product({
  _id: new mongoose.Types.ObjectId(),
  name: req.body.name,
  price: req.body.price,
  productImage: req.file.path
  });
  product
  .save()
  .then(result => {
  console.log(result);
  res.status(201).json({
    message: "Created product successfully",
    createdProduct: {
      name: result.name,
      price: result.price,
      _id: result._id,
      request: {
        type: "GET",
        url: "http://localhost:3000/products/" + result._id
      }
    }
  });
  })
  .catch(err => {
  console.log(err);

  res.status(500).json({

    error: err
  });
  });
  };

// 以下是我的产品路线

  router.post("/", checkAuth, upload.single('productImage'), 
  ProductsController.products_create_product);

标签: node.jsmulter

解决方案


使检查像

req.file? req.file.path : null

推荐阅读