添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am learning node.js with express template engine, I am following udemy course "learn node.js by building 10 projects", while following a lecture when professor run npm start localhost:3000 starts while mine pops up error indicating app.use requires middleware function I have tried matching code and its same. Please help me to resolve the error i have been stuck here for hours tried a lot of edits but its not working for me.

When I am trying to run 'npm start' following error pops up

TypeError: app.use() requires middleware functions

Here is app.js code:

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;

Here is package.json file

"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": "*"

Here is updated app.js (after removing 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;

Thank You

Step one in debugging an error is finding the line where the error occurred. Which line is 206 of /lib/application.js? – Kevin B Jul 27, 2015 at 15:06 I am really sorry but i lost access to my this new google account earlier, and somehow got access now, thanks for helping me :) – mean learner Dec 11, 2015 at 17:00

And be aware to have something like:

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

for the first case, or:

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

For the second one, in your html.

I was also doing that course & ran into the same problem. I resolved the error by following the Multer usage instructions from their github: https://github.com/expressjs/multer

Here is the code from their README:

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

& here is the code I used to overcome the error while doing that tutorial:

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

Hope it helps :)

I am really sorry but i lost access to my this new google account earlier, and somehow got access now, thanks for helping me :) – mean learner Dec 11, 2015 at 17:00

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.