typeerror: app.use() 需要中间件函数

Posted

技术标签:

【中文标题】typeerror: app.use() 需要中间件函数【英文标题】:typeerror: app.use() requires middleware function 【发布时间】:2015-10-17 19:41:56 【问题描述】:

我正在使用 express 模板引擎学习 node.js,我正在学习 udemy 课程“通过构建 10 个项目来学习 node.js”,同时在教授运行 npm start localhost:3000 开始时进行讲座,而我的弹出错误指示 app.use 需要中间件功能 我试过匹配代码和它的相同。请帮我解决我在这里停留了几个小时的错误尝试了很多编辑,但它对我不起作用。

当我尝试运行“npm start”时会弹出以下错误

TypeError: app.use() 需要中间件函数

这里是 app.js 代码:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

//Handle File Uploads
app.use(multer(
  dest: './uploads'
));

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded(
  extended: false
));

//Handle Express Sessions
app.use(session(
  secret: 'secret',
  saveUninitialied: true,
  resave: true
));

//Passport
app.use(passport.initialize());
app.use(passport.session());

//Validator
app.use(expressValidator(
  errorFormatter: function(param, msg, value) 
    var namespace = param.split('.'),
      root = namespace.shift(),
      formParam = root;

    while (namespace.length) 
      formParam += '[' + namespace.shift() + ']';
    
    return 
      param: formParam,
      msg: msg,
      value: value
    ;
  
));

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(flash());

app.use(function(req, res, next) 
  res.locals.messages = require('express-messages')(req, res);
  next();
);

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) 
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
);

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') 
  app.use(function(err, req, res, next) 
    res.status(err.status || 500);
    res.render('error', 
      message: err.message,
      error: err
    );
  );


// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) 
  res.status(err.status || 500);
  res.render('error', 
    message: err.message,
    error: 
  );
);



module.exports = app;

这是 package.json 文件


  "name": "nodeauth",
  "version": "1.0.0",
  "private": true,
  "scripts": 
    "start": "node ./bin/www"
  ,
  "dependencies": 
    "body-parser": "~1.12.4",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.12.4",
    "jade": "~1.9.2",
    "morgan": "~1.5.3",
    "serve-favicon": "~2.2.1",
    "mongodb": "*",
    "mongoose": "*",
    "connect-flash": "*",
    "express-validator": "*",
    "express-session": "*",
    "express-messages": "*",
    "passport": "*",
    "passport-local": "*",
    "passport-http": "*",
    "multer": "*"
  

这里是更新的 app.js(删除 multar 后)

var express          = require('express'),
    path             = require('path'),
    favicon          = require('serve-favicon'),
    logger           = require('morgan'),
    cookieParser     = require('cookie-parser'),
    expressValidator = require('express-validator'),
    session          = require('express-session'),
    passport         = require('passport'),
    LocalStrategy    = require('passport-local').Strategy,
    bodyParser       = require('body-parser'),
    flash            = require('connect-flash'),
    mongo            = require('mongodb'),
    mongoose         = require('mongoose'),

    db = mongoose.connection,

    routes = require('./routes/index'),
    users  = require('./routes/users'),

    app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// handle file uploads

//multer delted


// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded( extended: false ));

// handle express sessions
app.use(session(
  secret: 'keyboard cat',
  resave: true,
  saveUninitialized: true
));

// passport
app.use(passport.initialize());
app.use(passport.session());

// validator
app.use(expressValidator(
  errorFormatter: function(param, msg, value) 
    var namespace = param.split('.'),
        root      = namespace.shift(),
        formParam = root;

    while(namespace.length) 
      formParam += '[' + namespace.shift() + ']';
    

    return 
      param: formParam,
      msg  : msg,
      value: value
    ;
  
));

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// flash
app.use(flash());

// express messages
app.use(function(req, res, next) 
  res.locals.messages = require('express-messages')(req, res);
  next();
);

app.get('*', function(req, res, next) 
  res.locals.user = req.user || null;
  next();
);

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) 
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
);

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') 
  app.use(function(err, req, res, next) 
    res.status(err.status || 500);
    res.render('error', 
      message: err.message,
      error: err
    );
  );


// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) 
  res.status(err.status || 500);
  res.render('error', 
    message: err.message,
    error: 
  );
);


//Express server
var http = require('http');
var server = http.createServer(app);

app.get('/', function(req, res) 
    res.send("Hello World!");
);

server.listen(3000, 'localhost');
server.on('listening', function() 
    console.log('Express server started on port %s at %s', server.address().port, server.address().address);
);

module.exports = app;

谢谢

【问题讨论】:

需要详细补充错误! 我无法添加需要 10 分的图像 :( @Tushar :先生这里是错误截图的链接:postimg.org/image/hn8blsqi9 调试错误的第一步是找到发生错误的行。 /lib/application.js 的第 206 行是哪一行? 是express lib文件,代码不是我修改的, 【参考方案1】:

它是这样工作的。删除这一行,

app.use(multer( dest: './uploads' ));

并将其用作,

var multer = require('multer');
var upload = multer( dest: './uploads' );

我也走同样的路

【讨论】:

很抱歉,我之前无法访问我的新 Google 帐户,但现在不知何故可以访问了,感谢您的帮助 :) 我的答案比这个更年轻,更广泛,为什么不检查呢? 节点应该显示更具描述性的错误消息【参考方案2】:

变化:

//Handle File Uploads
app.use(multer(
  dest: './uploads'
));

例如:

app.use(multer(dest:'./uploads/').single('singleInputFileName'));

app.use(multer(dest:'./uploads/').array('multiInputFileName'));

并注意有类似的东西:

<form action="/postPhotos" enctype="multipart/form-data">
    <input type="file" name="singleInputFileName">
    <input type="submit" value="Upload photo">
</form>

对于第一种情况,或者:

<form action="/postPhotos" enctype="multipart/form-data">
    <input type="file" name="multiInputFileName" multiple>
    <input type="submit" value="Upload photo">
</form>

对于第二个,在您的 html 中。

【讨论】:

我已经删除了multer,但现在让我再次添加,【参考方案3】:

这对我有用:

app.use(multer(
  dest: path.join(__dirname, 'public/upload/temp')
).any());

【讨论】:

【参考方案4】:

我也在做那门课程并遇到了同样的问题。我按照他们 github 上的 Multer 使用说明解决了这个错误:https://github.com/expressjs/multer

这是他们自述文件中的代码:

    var multer  = require('multer')
    var upload = multer( dest: 'uploads/' )

&这里是我在做那个教程时用来克服错误的代码:

    var multer = require('multer');
    var upload = multer( dest: './uploads' );

希望对你有帮助:)

【讨论】:

真的很抱歉,我之前无法访问我的这个新的谷歌帐户,现在不知何故可以访问了,谢谢你的帮助:)【参考方案5】:

你可以简单地使用:

app.set(multer(dest: "./uploads"));

它也适用于我。

【讨论】:

【参考方案6】:

只改变这一行

app.use(multer(dest:'./uploads'));

var upload =multer(dest:'./uploads');

【讨论】:

【参考方案7】:

替换app.use(multer(dest:'./uploads'));

var upload = multer(dest:'./uploads');

为我工作。

【讨论】:

以上是关于typeerror: app.use() 需要中间件函数的主要内容,如果未能解决你的问题,请参考以下文章

错误:TypeError('app.use()需要中间件函数

不能 app.use(multer)。 “需要中间件功能”错误

中间件和 app.use 在 Expressjs 中的实际含义是啥?

node js app.use 抛出一个中间件函数

护照中间件不运行

express中的中间件