我正在写一个
博客应用程序
(单击该链接可查看
GitHub
存储库)
快递
EJS
和MongoDB。
我正在尝试介绍一个
添加帖子图片
功能。作为Express的新手,我对遇到的问题感到困惑。
添加帖子表单:
<%= typeof form!='undefined' ? form.bodyholder : '' %>
Upload an image
Cancel在控制器中我的
methos如下所示:
const Post = require('../../models/post');
const { validationResult } = require('express-validator');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/images')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + '.png')
}
});
const upload = multer({ storage: storage }).single('postimage');
exports.addPost = (req, res, next) => {
upload(function(err) {
if (err) {
console.log("There was an error uploading the image.");
}
res.json({
success: true,
message: 'Image uploaded!'
});
})
var form = {
titleholder: req.body.title,
excerptholder: req.body.excerpt,
bodyholder: req.body.body
};
const errors = validationResult(req);
const post = new Post();
post.title = req.body.title;
post.short_description = req.body.excerpt;
post.full_text = req.body.body;
if (!errors.isEmpty()) {
req.flash('danger', errors.array())
res.render('admin/addpost', {
layout: 'admin/layout',
website_name: 'MEAN Blog',
page_heading: 'Dashboard',
page_subheading: 'Add New Post',
form: form
});
} else {
post.save(function(err) {
if (err) {
console.log(err);
return;
} else {
req.flash('success', "The post was successfully added");
req.session.save(() => res.redirect('/dashboard'));
}
});
}
}我也有
在(控制器的)顶部。
“添加新帖子”表单运行良好,直到我尝试添加此上传功能。我目前使用的代码抛出了这个错误:
Cannot read property 'transfer-encoding' of undefined
at hasbody (C:\Path\To\Application\node_modules\type-is\index.js:93:21)我做错了什么?
发布于 2020-03-25 23:41:20
你不见了
和
在你的
,尝试添加这两个,如下所示
upload(req, res, function (err) {
if (err) {
console.log("There was an error uploading the image.");
}
res.json({
success: true,
message: 'Image uploaded!'
});
})https://stackoverflow.com/questions/60849398
复制相似问题