经常讨论的一个问题(错误消息:Router.use()需要中间件功能但是得到了一个Object),但是其他feed中的答案不起作用。例如
app.use(app.router);
routes.initialize(app);
此代码带来以下消息: 抛出新错误('\'app.router \'已被弃用!\ n请参阅3.x到4.x. 有关如何更新应用的详细信息,请参阅迁移指南。'); ^ 错误:'app.router'已弃用! 有关如何更新应用的详细信息,请参阅3.x到4.x迁移指南。
我希望会有更好的主意。
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
//mongoose.connect('mongodb://localhost/dbname');
//var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
//Init App
var app = express();
//View Engine
app.set('views',path.join(__dirname,'views'));
app.engine('handlebars', exphbs({defaultLayout: 'layout'}));
app.set('view engine','handlebars');
//BodyParser Middleware
app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(urlencodedParser);
app.use(cookieParser());
//Set Static Folder
app.use(express.static(path.join(__dirname,'public')));
//Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
//Passprt init
app.use(passport.initialize());
app.use(passport.session());
//Express 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
};
}
}));
//Connect Flash
app.use(flash());
//Global Vars
app.use(function(req,res, next) {
res.locals.success_msg = req.flash('succes_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
//Set Routes
app.use('/', require('./routes/index'));
app.use('/users', require('./routes/users'));
// Set Port
app.set('port',(process.env.PORT || 3000));
//Start Server
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});