I can't add a post, I think the problem is connected with fileupload.
Here is the error:
TypeError: Cannot read property 'name' of undefined
at addPost (C:\Users\Web-Developer\Desktop\crud-app\routes\post.js:21:37)
at Layer.handle [as handle_request] (C:\Users\Web-Developer\Desktop\crud-app\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Web-Developer\Desktop\crud-app\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\Web-Developer\Desktop\crud-app\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Web-Developer\Desktop\crud-app\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Web-Developer\Desktop\crud-app\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\Web-Developer\Desktop\crud-app\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\Web-Developer\Desktop\crud-app\node_modules\express\lib\router\index.js:275:10)
at C:\Users\Web-Developer\Desktop\crud-app\node_modules\express-fileupload\lib\processMultipart.js:140:9
at processTicksAndRejections (internal/process/task_queues.js:97:5)
Here is my code :
addPost: (req, res) => {
if (!req.files) {
return res.status(400).send("No files were uploaded.");
}
let message = '';
let title = req.body.title;
let description = req.body.description;
let category = req.body.category;
let date = req.body.date;
let main_image = req.files.main_image;
let image_name = main_image.name;
let fileExtension = main_image.mimetype.split('/')[1];
image_name = title + '.' + fileExtension;
let titleQuery = "SELECT * FROM `posts` WHERE title = '" + title + "'";
db.query(titleQuery, (err, result) => {
if (err) {
return res.status(500).send(err);
}
if (result.length > 0) {
message = 'Post already exists';
res.render('add-player.ejs', {
message,
title: 'Welcome to BLOG'
});
} else {
// check the filetype before uploading it
if (main_image.mimetype === 'image/png' || main_image.mimetype === 'image/jpeg' || main_image.mimetype === 'image/gif') {
// upload the file to the /public/assets/img directory
main_image.mv(`public/assets/img/${image_name}`, (err ) => {
if (err) {
return res.status(500).send(err);
}
// send the post's details to the database
let query = "INSERT INTO `posts` (title, description, category, date, main_image) VALUES ('" +
title + "', '" + description + "', '" + category + "', '" + date + "', '" + image_name + "')";
db.query(query, (err, result) => {
if (err) {
return res.status(500).send(err);
}
res.redirect('/');
});
});
} else {
message = "Invalid File format. Only 'gif', 'jpeg' and 'png' images are allowed.";
res.render('add-player.ejs', {
message,
title: 'Welcome to BLOG'
});
}
}
});
}