javascript - 类型错误 : Cannot read property 'location' of undefined

标签 javascript angularjs node.js amazon-web-services angular5

一直在尝试使用 AWS S3(Multer 和 MulterS3)发布带有图像的产品。每次我使用 postman 时,我都会收到“TypeError:无法读取未定义的属性‘位置’”,这是我拥有 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;

最佳答案

您的 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'
    });
});

关于javascript - 类型错误 : Cannot read property 'location' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53931773/

相关文章:

javascript - 意外语法错误 : "\n" in javascript/jquery

javascript - 当正方形到达 Canvas 底部时会卡住

javascript - Firebase 单元测试错误 - 无法解析 Firebase 网址

javascript - AngularJS:在链接方法中添加指令的范围

javascript - 表达式值未在 View 中更新

node.js - EC2 实例 'took too long to respond'

javascript - 如何从 AngularJS 服务将变量发送到 NodeJS Controller ?

javascript - 客户端发送值到node.js并设置为cookie

javascript - Angular 谷歌地图中标记信息显示的错误

node.js - 创建付款时结帐时出现此错误 "Bad request - parameter error"