У меня следующая ошибка:
Cannot read property 'passport' of undefined
TypeError: Cannot read property 'passport' of undefined
at /home/inuke/rendu/web-dev/dashboard/dashboard/routes/index.js:13:20
at Layer.handle [as handle_request] (/home/inuke/rendu/web-dev/dashboard/dashboard/node_modules/express/lib/router/layer.js:95:5)
at next (/home/inuke/rendu/web-dev/dashboard/dashboard/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/inuke/rendu/web-dev/dashboard/dashboard/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/inuke/rendu/web-dev/dashboard/dashboard/node_modules/express/lib/router/layer.js:95:5)
at /home/inuke/rendu/web-dev/dashboard/dashboard/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/inuke/rendu/web-dev/dashboard/dashboard/node_modules/express/lib/router/index.js:335:12)
at next (/home/inuke/rendu/web-dev/dashboard/dashboard/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/home/inuke/rendu/web-dev/dashboard/dashboard/node_modules/express/lib/router/index.js:174:3)
at router (/home/inuke/rendu/web-dev/dashboard/dashboard/node_modules/express/lib/router/index.js:47:12)
at Layer.handle [as handle_request] (/home/inuke/rendu/web-dev/dashboard/dashboard/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/inuke/rendu/web-dev/dashboard/dashboard/node_modules/express/lib/router/index.js:317:13)
at /home/inuke/rendu/web-dev/dashboard/dashboard/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/inuke/rendu/web-dev/dashboard/dashboard/node_modules/express/lib/router/index.js:335:12)
at next (/home/inuke/rendu/web-dev/dashboard/dashboard/node_modules/express/lib/router/index.js:275:10)
at expressInit (/home/inuke/rendu/web-dev/dashboard/dashboard/node_modules/express/lib/middleware/init.js:40:5)
И я не могу понять, почему она не работает.
Вот мой app.js:
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const session = require('express-session');
const passport = require('passport');
const Account = require('./models/account');
const LocalStrategy = require('passport-local').Strategy;
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use(session({
cookieName: 'session',
secret: 'hamzasaucegod',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Вот мой файл account.js:
const passport = require('passport');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const passportLocalMongoose = require('passport-local-mongoose');
const Account = new Schema({
username: String,
password: String
});
Account.plugin(passportLocalMongoose);
module.exports = mongoose.model('Account', Account);
И, наконец, вот мой файл index.js, который содержит ошибку, которую я считаю:
const express = require('express');
const passport = require('passport');
const Account = require('../models/account');
const router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Dashboard', user : req.user, error : null });
});
router.get('/register', function(req, res) {
if ( req.session.passport.user != null ) {
res.redirect('/');
} else {
res.render('register', {
title : 'Sign-up'
});
}
});
router.post('/register', function(req, res, next) {
Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
if (err) {
return res.render('register', { error : err.message });
}
passport.authenticate('local')(req, res, function () {
req.session.save(function (err) {
if (err) {
return next(err);
}
res.redirect('/');
});
});
});
});
router.get('/login', function(req, res) {
if ( req.session.passport.user != null ) {
res.redirect('/');
} else {
res.render('login', {
user : req.user,
title : 'Sign-in',
subTitle : 'Come back please !'
});
}
});
router.post('/login', passport.authenticate('local'), function(req, res) {
if ( req.session.passport.user != null ) {
res.redirect('/');
} else {
res.redirect('/register');
}
});
router.get('/logout', function(req, res) {
if ( req.session.passport.user != null ) {
req.logout();
res.redirect('/');
}
else {
res.redirect('/')
}
});
module.exports = router;
Я пыталсянекоторые вещи, но в итоге я получил больше ошибок, поэтому я подумал, что будет лучше дать вам оригинальный код.Я не знаю, почему это не работает.Каждый раз, когда я загружаю / регистрирую или / логин это печатает ошибку ниже.