首页 > 解决方案 > 未定义:即使使用 upload.single() 中间件,req.file() 也会输出未定义

问题描述

// Models
var mongoose = require('mongoose');

var ProfileSchema = new mongoose.Schema({

    fullName: {
        type: String,
        required: true
    }
      //  profileImage: {type: String, required: true}



});

module.exports = mongoose.model('Profile', ProfileSchema)



// Controllers
var Profile = require('../models/profile');
var multer = require('multer');
var upload = multer({dest: 'uploads/'});


exports.createProfile = (upload.single('profileImage'), function (req, res, next) {
    
    var profileData = {
        fullName: req.body.fullName,
        // profileImage: req.file
    }
    console.log(req.file);
    console.log('req.file: ', JSON.stringify(req.file));     
    console.log(profileData);
        Profile.create(profileData, function (err, profile) {
        if (err) {
            // console.log(err);
            res.end();
            return;
            // res.send(err);
        }
        Profile.create(function (err, profiles) {
            if (err) {
                res.end();
                // res.send(err);
                return;
            }
            
            res.json(profileData);
        });
    });
});

我正在尝试使用中间件在 MongoDB 数据库中同时添加文本和图像。但是,我的字段没有填充,当我尝试在控制台中打印它时,它显示 req.file(): undefined。我研究了其他问题,并指出使用“upload.single()”将解决问题。在我的情况下,它没有!第一部分是我的模型视图(架构),第二部分是我的控制器视图。

标签: node.jsexpressmulter

解决方案


推荐阅读