node.js - express+multer抛出错误:'app.use() requires middleware functions'
ringa_lee
ringa_lee 2017-04-17 12:59:06
0
4
1315

利用node,想要通过表单传递值,node的代码如下:

var express=require('express'),
    //form的get方法使用url模块
    url=require('url'),
    //form的post方法使用url模块
    bodyParser=require('body-parser'),
    multer=require('multer'),
    util=require('util'),
    app=express();

app.use(multer({dest:'./'}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

app.get('/',function(req,res){
    res.sendfile('./index.html');
});

app.post('/reg',function(req,res){//页面是post,服务器端也是要post
    var urlObj=url.parse(req.url,true);
    res.write(util.inspect(req.files));
    res.end(JSON.stringify(req.body));
});

app.listen(8080);

目前express版本是4.13.3,multer的版本是1.0.1

运行抛出的错误如下:

throw new TypeError('app.use() requires middleware functions');

在stackoverflow上查找到类似的问题,但是他的原因是所使用的包的问题stackoverflow问题。
我查看了multer的文档,好像它并没有做出类似的改变。特意向大家请教这个问题

ringa_lee
ringa_lee

ringa_lee

reply all(4)
刘奇

This problem has been solved. It is a problem with the multer version. Multer requires version 0.1.8.

npm install multer@0.1.8 
迷茫

I have now upgraded multer 1.1.0 and encountered the same problem, so I went to his official website to find out more.

You can no longer write like this

app.use(multer({dest:'./'}));

You need to write it in the route

var multer = require('multer');

var upload = multer({dest: './public/images/user'});

router.post('/upload', upload.fields([
    {name: 'file1'},
    {name: 'file2'},
    {name: 'file3'},
    {name: 'file4'},
    {name: 'file5'}
]), function(req, res, next){
    for(var i in req.files){
        console.log(req.files[i]);
    }
    req.flash('success', '文件上传成功!');
    res.redirect('/upload');
});

The above example is that I submitted 5 names at the same time.
It provides 3 methods. single() .array() .fields()
.single() is a file
For example

upload.single('avatar')//avatar是name名

.array() is multiple files with the same name
such as

upload.array('photos', 12)//photos是name名,第二个参数是最大12个为name名的文件

.fields() is multiple files
such as

upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
//maxCount是可选

Hope to help future nodejs learners

阿神

I also encountered this problem, have you solved it?

洪涛

I also encountered this problem today, and I studied it by the way today. If you want to use the v1.1.0 version, you can refer to my code

// 文件上传插件
var multer = require('multer');
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/images/user')
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname)
  }
});
var upload = multer({ storage: storage });
var cpUpload = upload.any();
app.use(cpUpload);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template