我正在使用blogging application,Express和MongoDB开发EJS(单击链接以查看GitHub回购)。>
我正在尝试引入添加帖子图像
功能。对Express来说还很陌生,我对遇到的问题感到困惑。添加帖子的形式:
<form action="/dashboard/post/add" method="POST" enctype="multipart/form-data" class="mb-0"> <div class="form-group"> <input type="text" class="form-control" name="title" value="<%= typeof form!='undefined' ? form.titleholder : '' %>" placeholder="Title" /> </div> <div class="form-group"> <input type="text" class="form-control" name="excerpt" value="<%= typeof form!='undefined' ? form.excerptholder : '' %>" placeholder="Excerpt" /> </div> <div class="form-group"> <textarea rows="5" class="form-control" name="body" placeholder="Full text"><%= typeof form!='undefined' ? form.bodyholder : '' %></textarea> </div> <label for="postimage">Upload an image</label> <div class="form-group"> <input type="file" name="postimage" id="postimage" size="20"> </div> <div class="form-group d-flex mb-0"> <div class="w-50 pr-1"> <input type="submit" value="Add Post" class="btn btn-block btn-md btn-success"> </div> <div class="w-50 pl-1"> <a href="/dashboard" class="btn btn-block btn-md btn-success">Cancel</a> </div> </div> </form>
在控制器中,我的
addPost()
方法看起来像这样:
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')); } }); } }
我也将
const multer = require("multer");
放在(控制器的顶部)。
在我尝试添加此上传功能之前,“添加新帖子”表单可以正常工作。我当前拥有的代码抛出此错误:
Cannot read property 'transfer-encoding' of undefined at hasbody (C:\Path\To\Application\Application\node_modules\type-is\index.js:93:21)
我在做什么错?
我正在使用Express,EJS和MongoDB开发博客应用程序(单击链接以查看GitHub存储库)。我正在尝试介绍添加帖子图片功能。我对Express相当陌生,我是...
您在req
中缺少res
和upload()
,请尝试添加这两个像upload(
req,res