我能够将一个非常简单的中间件(isAuthenticated)移动到外部中间件文件,但是我更难以将我的multer上传移动。我刚学会了如何将它们移动到单独的文件中,所以它可能是显而易见的。
routes/index.js
var middleware = require('../middleware/common');
var isAuthenticated = middleware.isAuthenticated;
var upload = middleware.multerSetup;
...
router.post('/updateuser',
upload,
...,
function (req, res, next) {
res.redirect('/dashboard');
}
);
-
//middleware/common.js
var multer = require('multer');
Middleware = {
//Checks whether user is logged in
isAuthenticated: function(req,res,next){
if(req.isAuthenticated()){
return next();
}
req.flash('auth',"You do not have the proper permissions to access this page");
res.redirect('/');
},
multerSetup: function(req,res,next){
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/uploads/')
},
//detects file type, then adds extension to match file type
filename: function (req, file, cb) {
var ext = "";
switch(file.mimetype){
case 'image/png':
ext = '.png';
break;
case 'image/jpeg':
ext = '.jpeg';
break;
default:
ext = '';
}
cb(null, Date.now() + ext); //Appending .jpg
}
});
var upload = multer({storage:storage, fileFilter: function (req, file, cb) {
var acceptedExt = ['.png','.jpg','.gif','.bmp'];
if (req.hasOwnProperty('file') && acceptedExt.indexOf(path.extname(file.originalname))=== -1) {
return cb(new Error('Image type not allowed: ' + path.extname(file.originalname)));
}
cb(null, true)
}});
return upload.single('upl');
}
};
module.exports = Middleware;
错误:
routes\index.js:108
upload.single('upl'),
^
TypeError: upload.single is not a function
at Object.<anonymous> (C:\Users\Tyler\WebstormProjects\volunteer\volunteerApp\routes\index.js:108:12)
答案 0 :(得分:0)
您正在设置您的multer中间件错误。您的Middleware.multerSetup
是一个中间件函数,然后调用upload.single
来设置multer(然后调用multer,然后请求挂起)。将您的multer上传设置移到自定义中间件之外,让模块从upload.single
导出返回函数。
示例:
Middleware = {
...
multerSetup: upload.single('upl')
...
}
答案 1 :(得分:0)
知道了!只需要将routes / index.js中的上传定义为函数。
var upload = middleware.multerSetup();