当我尝试上传一些图片或点击未选择图片的上传时出现此错误:
TypeError: Cannot read property 'image' of undefined
at E:\WEB\WebProjekat\routes\admin_products.js:58:38
at Layer.handle [as handle_request] (E:\WEB\WebProjekat\node_modules\express\lib\router\layer.js:95:5)
at next (E:\WEB\WebProjekat\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (E:\WEB\WebProjekat\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (E:\WEB\WebProjekat\node_modules\express\lib\router\layer.js:95:5)
at E:\WEB\WebProjekat\node_modules\express\lib\router\index.js:281:22
at Function.process_params (E:\WEB\WebProjekat\node_modules\express\lib\router\index.js:335:12)
at next (E:\WEB\WebProjekat\node_modules\express\lib\router\index.js:275:10)
at Function.handle (E:\WEB\WebProjekat\node_modules\express\lib\router\index.js:174:3)
at router (E:\WEB\WebProjekat\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (E:\WEB\WebProjekat\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (E:\WEB\WebProjekat\node_modules\express\lib\router\index.js:317:13)
at E:\WEB\WebProjekat\node_modules\express\lib\router\index.js:284:7
at Function.process_params (E:\WEB\WebProjekat\node_modules\express\lib\router\index.js:335:12)
at next (E:\WEB\WebProjekat\node_modules\express\lib\router\index.js:275:10)
at E:\WEB\WebProjekat\app.js:90:3
这是表格的样子:http://prntscr.com/nlmeq4
我遵循了youtube上的一些教程,其中他使用了完全相同的代码,并且对他有用。
这是Admin_products和app.js的代码
admin_products.js:
var express = require('express');
var router = express.Router();
var mkdirp = require('mkdirp');
var fs = require('fs-extra');
var resizeImg = require('resize-img');
//Get product model
var Product = require('../models/product');
//Get Category model
var Category = require('../models/category');
/*
* GET products index
*/
router.get('/', function (req, res) {
var count;
Product.count(function (err, c) {
count = c;
});
Product.find(function (err, products) {
res.render('admin/proizvodi', {
products: products,
count: count
});
});
});
/*
* GET add products
*/
router.get('/dodaj-proizvod', function (req, res) {
var title = "";
var desc = "";
var price = "";
Category.find(function (err, categories) {
res.render('admin/dodaj_proizvod', {
title: title,
desc: desc,
categories: categories,
price: price
});
});
});
/*
* POST add products index
*/
router.post('/dodaj-proizvod', function (req, res) {
var imageFile = typeof req.files.image !== "undefined" ? req.files.image.name : "";
req.checkBody('title', 'Morate uneti naziv proizvoda.').notEmpty();
req.checkBody('desc', 'Morate uneti opis proizvoda.').notEmpty();
req.checkBody('price', 'Morate uneti cenu proizvoda.').isDecimal();
req.checkBody('image', 'Morate uploadovati sliku proizvoda').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/dodaj_proizvod', {
errors: errors,
title: title,
desc: desc,
categories: categories,
price: price
});
});
} else {
Product.findOne({slug: slug}, function (err, product) {
if (product) {
req.flash('danger', 'Uneli ste naslov proizvoda koji vec postoji, izaberite drugi.');
Category.find(function (err, categories) {
res.render('admin/dodaj_proizvod', {
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/slike_proizvoda/'+product._id, function (err) {
return console.log(err);
});
mkdirp('public/slike_proizvoda/'+product._id + '/galerija', function (err) {
return console.log(err);
});
mkdirp('public/slike_proizvoda/'+product._id + '/galerija/ikonice', function (err) {
return console.log(err);
});
if (imageFile != "") {
var productImage = req.files.image;
var path = 'public/slike_proizvoda/'+product._id + '/' + imageFile;
productImage.mv(path, function (err) {
return console.log(err);
});
}
req.flash('success', 'Proizvod je dodat!');
res.redirect('/admin/proizvodi');
});
}
});
}
});
//Exports
module.exports = router;`
app.js:
var express = require('express');
var path = require('path');
var mongoose = require('mongoose');
var config = require('./config/database');
var bodyParser = require('body-parser');
var Busboy = require('busboy');
var session = require('express-session');
var expressValidator = require('express-validator');
var fileUpload = require('express-fileupload');
// Connect to db
mongoose.connect(config.database, {useNewUrlParser: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('Connected to mongoDB')
});
// Init app
var app = express();
// View engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// Set public foler
app.use(express.static(path.join(__dirname, 'public')));
// Set global errors variable
app.locals.errors = null;
// Express fileUpload middlware
app.use(fileUpload());
// Body Parser middleware
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// Express Session middleware
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true,
//cookie: { secure: true }
}));
// Express Validator middleware
app.use(expressValidator({
errorFormater: function(param,msg,value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length){
formParam += '[' + namespace.shift() + ']';
}
return{
param : formParam,
msg : msg,
value: value
};
},
customValidators: {
isImage: function (value, filename) {
var extension = (path.extname(filename)).toLowerCase();
switch(extension) {
case '.jpg':
return '.jpg';
case '.jpeg':
return '.jpeg';
case '.png':
return '.png';
case '':
return '.jpg';
default:
return false;
}
}
}
}));
// Express Messages middleware
app.use(require('connect-flash')());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
// Set routs
var pages = require('./routes/pages.js');
var adminPages = require('./routes/admin_pages.js');
var adminCategories = require('./routes/admin_categories.js');
var adminProducts = require('./routes/admin_products.js');
app.use('/admin/stranice', adminPages);
app.use('/admin/kategorije', adminCategories);
app.use('/admin/proizvodi', adminProducts);
app.use('/', pages);
// Start the server
var port = 3000;
app.listen(port, function(){
console.log('Server started on port ' + port);
});`