【问题标题】:TypeError: Cannot read property 'image' of null expressjsTypeError:无法读取空 expressjs 的属性“图像”
【发布时间】:2022-01-12 17:28:35
【问题描述】:

我正在用 express 和 mongodb 构建一个购物车。但是,当我尝试将图像类别添加到表单时,出现错误; post admin_product.js 的代码

router.post('/add-product', function (req, res) {

var imageFile = typeof req.files.image !== "undefined" ? req.files.image.name: "";

req.checkBody('title', 'Title must have a value.').notEmpty();
req.checkBody('desc', 'Description must have a value.').notEmpty();
req.checkBody('price', 'Price must have a value.').isDecimal();
req.checkBody('image', 'You must upload an image').isImage(imageFile);

var title = req.body.title;
var slug = title.replace(/\s+/g, '-').toLowerCase();
var desc = req.body.desc;
var price = req.body.price;
var category = req.body.category;

var errors = req.validationErrors();

if (errors) {
    Category.find(function (err, categories) {
        res.render('admin/add_product', {
            errors: errors,
            title: title,
            desc: desc,
            categories: categories,
            price: price
        });
    });
} else {
    Product.findOne({slug: slug}, function (err, product) {
        if (product) {
            req.flash('danger', 'Product title exists, choose another.');
            Category.find(function (err, categories) {
                res.render('admin/add_product', {
                    title: title,
                    desc: desc,
                    categories: categories,
                    price: price
                });
            });
        } else {

            var price2 = parseFloat(price).toFixed(2);

            var product = new Product({
                title: title,
                slug: slug,
                desc: desc,
                price: price2,
                category: category,
                image: imageFile
            });

            product.save(function (err) {
                if (err)
                    return console.log(err);

                mkdirp('public/product_images/' + product._id, function (err) {
                    return console.log(err);
                });

                mkdirp('public/product_images/' + product._id + '/gallery', function (err) {
                    return console.log(err);
                });

                mkdirp('public/product_images/' + product._id + '/gallery/thumbs', function (err) {
                    return console.log(err);
                });

                if (imageFile != "") {
                    var productImage = req.files.image;
                    var path = 'public/product_images/' + product._id + '/' + imageFile;

                    productImage.mv(path, function (err) {
                        return console.log(err);
                    });
                }

                req.flash('success', 'Product added!');
                res.redirect('/admin/products');
            });
        }
    });
}

});

当我提交表单而不上传图片时出现错误: TypeError: Cannot read property 'image' of null

从错误声明中,问题似乎出在这一行 var imageFile = typeof req.files.image !== "undefined" ? req.files.image.name: "";

.ejs:

<input type="text" class = "form-control" name ="title" value = "<%= title%>" placeholder =  "Title">
</div>

<div class = "form-group">
 <label for="">Description</label>
 <textarea name="desc" id = "ta" class="form-control" cols="30" rows="10" placeholder="Description"><%= desc %></textarea>
</div>


    <div class="form-group">
        <label for="">Category</label>
        <select name="category" class="form-control">
            <% catagories.forEach(function(cat){ %>
                <option value="<%= cat.slug %>"><%= cat.title %></option>
            <% }); %>
        </select>
    </div>

app.js:

const pages = require('./routes/pages.js');
const adminPages = require('./routes/admin_pages.js');
const adminCatagories = require('./routes/admin_catagories.js');
const adminProducts = require('./routes/admin_products.js');

app.use('/', pages);
app.use('/admin/pages', adminPages);
app.use('/admin/catagories', adminCatagories);
app.use('/admin/products', adminProducts);

我在教程中看到完全相同的代码工作得很好,但我自己却没有弄对

【问题讨论】:

  • 所以如果它没有 files 属性,你似乎必须处理你的 req
  • req.files.image !== "undefined" 尝试不带引号的undefined
  • @M-Raw 试过还是一样的结果
  • @MWO 我该怎么做
  • @FuruiCoder 类似的东西? var imageFile = req?.files?.image? req.files.image.name: "";

标签: javascript node.js express


【解决方案1】:

通过 if else 语句解决了这个问题。而不是这个

var imageFile = typeof(req.files.image) !== "undefined" ? req.files.image.name : "";

我写了这个:

if (!req.files) { 
        imageFile =""; }

   if (req.files) {

   var imageFile = typeof(req.files.image) !== "undefined" ? req.files.image.name : "";}

效果很好。希望对其他人也有帮助

【讨论】:

  • 你可以改用req.files?.image?.name || ''
  • 试过了。有用。谢谢
猜你喜欢
  • 1970-01-01
  • 2016-04-20
  • 2020-11-25
  • 1970-01-01
  • 2021-12-10
  • 2014-10-20
  • 2020-12-15
  • 1970-01-01
  • 2022-01-12
相关资源
最近更新 更多