app.use()需要一个中间件功能

时间:2017-11-10 05:38:11

标签: javascript node.js express

我是node和express的新手,当我运行节点app.js时我正在制作logapp它显示错误app.use()需要一个中间件功能我安装所有运行项目所需的npm是否有任何解决这个问题的方法我真的不明白我做错了什么。任何帮助提前谢谢。这是我的app.js代码

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validators');
var flash = require('connect-flash');
var session  = require('express-sessions');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;


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

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view', 'handlebars');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

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


app.use(session({
    secret: 'secret',
    saveUninitialized:true,
    resave: true
}));

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

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(flash());

app.use(function(req, res, next) {
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    next();
})


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


app.set('port', (process.env.PORT || 3000 ));

app.listen(app.get('port'), function(){
    console.log('Server started on Port ' + app.get('port'));
})

1 个答案:

答案 0 :(得分:0)

我认为你使用了错误的npm模块。而不是

var expressValidator = require('express-validators');

使用

var expressValidator = require('express-validator');