错误:未使用中间件中的passport.initialize()

时间:2018-11-03 11:16:43

标签: node.js

我正在使用护照创建登录名。但是有一个错误 “未使用passport.initialize()中间件”。     

var createError = require('http-errors');
var express = require('express');
var session = require('express-session');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var sassMiddleware = require('node-sass-middleware');
var flash = require('connect-flash');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var mongoose = require('mongoose');
var passport = require('passport');
var db = mongoose.connection;
var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(sassMiddleware({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public'),
  indentedSyntax: true,
  sourceMap: true
}));
app.use(express.static(path.join(__dirname, 'public')));

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

app.use(flash());
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use(function(req, res, next) {
  next(createError(404));
});

app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  res.status(err.status || 500);
  res.render('error');
});
mongoose.connect('mongodb://localhost/27017');
mongoose.Promise = global.Promise; 
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
    console.log("mongo DB connected...")
});

require('./config/passport')(passport);
app.use(passport.initialize());
app.use(passport.session());

module.exports = app;
为什么会出现错误? 我已经考虑了很长时间,但尚未解决。 因为我是初学者,所以此错误很难。 请帮我解决。

1 个答案:

答案 0 :(得分:0)

例如,您必须使用初始化的护照中间件:

const pasportLocal = require('passport-local');    

在app.use(passport.session())之后添加此内容

passport.use(new passportLocal.Strategy(function(username, passport, done){
//Your code ...
}));

请遵循护照文档以获取与护照配置有关的更多信息。