Express.js application bug causes Route.post() requires a callback function but got a [object Undefined] error

≡放荡痞女 提交于 2020-04-18 03:54:57

问题


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 with Multer. Being quite new to Express, I run into trouble.

In utils\imageupload.js I have added:

const multer = require("multer");

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

exports.upload = multer({ storage: storage }).single('postimage');

I import and use that in my dashboard routes file:

const imageUploader = require('../../utils/validation.js');

//more code

// Add Post
router.post('/post/add', imageUploader.upload, validator.addPostCheck, dashboardController.addPost);

//more code

In the controller I have (among others):

exports.addPost = (req, res, next) => {

    upload(req, res, function(err) {
        if (err) {
            console.log("There was an error uploading the image.");
        } else {
            res.sendStatus(200);
        }
    })

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

As long as the line imageUploader.upload is in the controller, the entire application just crashes, with the error: Route.post() requires a callback function but got a [object Undefined] error.

What am I doing wrong?


回答1:


You have the following line:

const imageUploader = require('../../utils/validation.js');

validation.js does not export upload which you are using here:

// Add Post
router.post('/post/add', imageUploader.upload, validator.addPostCheck, dashboardController.addPost);

Changing the import to

const imageUploader = require('../../utils/imageupload.js');

should fix the problem.

Regarding the problem in the admin dashboard-controller: Since you've already called the multer upload, you can remove it in addPost, req should now contain the uploaded file.

exports.addPost = (req, res, next) => {
    // removed the upload code
    var form = {
            titleholder: req.body.title,
            excerptholder: req.body.excerpt,
            bodyholder: req.body.body
    };
    ...



回答2:


It's throw such type of error when you router unable to call you method please check calling method in router.



来源:https://stackoverflow.com/questions/61142162/express-js-application-bug-causes-route-post-requires-a-callback-function-but

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