Express.js application bug: Cannot read property 'transfer-encoding' of undefined

房东的猫 提交于 2020-04-07 08:07:38

问题


I am working on a blogging application (click the link to see the GitHub repo) with Express, EJS and MongoDB.

I am trying to introduce an add post image feature. Being quite new to Express, I am puzzled about the problem I have ran into.

The add post form:

<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>

In the controller my addPost() methos looks like this:

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'));
            }
        });
    }
}

I alse have const multer = require("multer"); at the top (of the controller).

The "Add New Post" form worked fine until I tried to add this upload feature. The code I currently have throws this error:

Cannot read property 'transfer-encoding' of undefined
    at hasbody (C:\Path\To\Application\node_modules\type-is\index.js:93:21)

What am I doing wrong?


回答1:


You are missing req and res inside your upload(), try adding those two like upload(req,res, function (err){

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/express-js-application-bug-cannot-read-property-transfer-encoding-of-undefine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!