尝试使用AWS S3(Multer和MulterS3)发布带有图像的产品。每次我使用邮递员时,都会收到“ TypeError:无法读取未定义的属性'location'”,这是我拥有Image变量的那一行。我做错了什么?
这是我的代码:
const router = require('express').Router();
const Product = require('../models/product');
const aws = require('aws-sdk');
const multer = require('multer');
const multerS3 = require('multer-s3');
const s3 = new aws.S3({ accessKeyId: "--", secretAccessKey: "--"});
const checkJWT = require('../middlewares/check-jwt');
var upload = multer({
storage: multerS3({
s3: s3,
bucket: '365techhubwebapplication',
metadata: function(req, file, cb) {
cb(null, {fieldName: file.fieldName});
},
key: function (req, file, cb) {
cb(null, Date.now().toString())
}
})
});
router.route('/products')
.get((req, res, next) => {
res.json({
success: "Hello"
});
})
.post([checkJWT, upload.single('product_picture')], (req, res, next) => {
console.log(upload);
console.log(req.file);
let product = new Product();
product.owner = req.decoded.user._id;
product.category = req.body.categoryId;
product.title = req.body.title;
product.price = req.body.price;
product.description = req.body.description;
product.image = req.file.location;
product.save();
res.json({
success: true,
message: 'Successfully Added the product'
});
});
module.exports = router;
答案 0 :(得分:0)
您的req.file未定义,请发送req.file或添加检查并更新您的代码,如下所示:
.post([checkJWT, upload.single('product_picture')], (req, res, next) => {
console.log(upload);
console.log(req.file);
let product = new Product();
product.owner = req.decoded.user._id;
product.category = req.body.categoryId;
product.title = req.body.title;
product.price = req.body.price;
product.description = req.body.description;
if (req.file) { // Checking if req.file is not empty.
product.image = req.file.location;
}
product.save();
res.json({
success: true,
message: 'Successfully Added the product'
});
});