尝试访问节点js中的req.user属性时,无法读取未定义的属性“username”

时间:2017-01-06 14:49:36

标签: node.js express passport.js

我正在使用MEAN Stack。我想访问req.user属性。但是当我尝试显示当前用户的用户名时,我收到错误无法读取未定义的属性'用户名'。我参考了一些网站。 https://www.airpair.com/express/posts/expressjs-and-passportjs-sessions-deep-dive

类似问题Node + Express + Passport: req.user Undefined

已经提到中间件功能的顺序很重要。我纠正了那些。我仍然得到同样的错误。我的错是什么?

  

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var mongoose = require("mongoose");
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 ConnectRoles = require('connect-roles');
var User = require('./models/user');


mongoose.connect("mongodb://localhost:27017/test"); 
var db = mongoose.connection;

db.on("error", console.error.bind(console, "Connection error:"));
db.once("open", function(callback){
    console.log("Connection Succeeded."); 
});

var routes = require('./routes/Login');
var admin = require('./routes/AdminDatabase');
var survey = require('./routes/CreateSurvey');
var submit = require('./routes/SubmitSurvey');

var app = express();

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

app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

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

app.use(passport.initialize());
app.use(passport.session());
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');
  res.locals.user = req.user || null;

  next();
});

app.use('/', routes);
app.use('/AdminDatabase', admin);
app.use('/CreateSurvey', survey);
app.use('/SubmitSurvey', submit);

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});


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
  });
}


app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

app.get('/AdminDatabase', function(req, res){
    user.find({}, function(err, profile){
        res.render('AdminDatabase', {profile:profile});  
    });
});
module.exports = app;
  

Login.js(我有护照和路线)

var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
var ConnectRoles = require('connect-roles');

router.get('/', function(req, res, next) {
  res.render('Login', { title: 'Login' });
});

passport.serializeUser(function(user, done) {
    done(null, user._id);
});
passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
    done(err, user);
    });
});

passport.use("/", new LocalStrategy(
     function(username, password, done) {
        User.findOne({ username: username }, function(err, user) {
            if (err) { return done(err); }

            if (!user) {
                return done(null, false,
                 { message: "No user has that username!" });
            }

            user.checkPassword(password, function(err, isMatch) {

            if (err) { return done(err); }
                if (isMatch) {
                    return done(null, user);
                } else {
                    return done(null, false,{ message: "Invalid password." });
            }
        });
    });
}));

router.use(function(req, res, next) {
    res.locals.currentUser = req.user;
    res.locals.errors = req.flash("error");
    res.locals.infos = req.flash("info");

    next();
});

router.post("/", passport.authenticate("/", {
    successRedirect: "/SubmitSurvey",
    failureRedirect: "/",
    session: false,
    failureFlash: true
}));

router.get("/AdminDatabase", function(req, res) {
   res.render('AdminDatabase', { title: 'AdminDatabase' });
 });

router.get('/CreateSurvey', function(req, res, next) {
  res.render('CreateSurvey', { title: 'CreateSurvey' });
});

router.get('/SubmitSurvey', function(req, res, next) {
  res.render('SubmitSurvey', { title: 'SubmitSurvey' });
});

router.get('/profile', function(req, res){
  var user= res.user;
  res.render('profile', { title: 'profile', user: user });
});

router.get("/Logout", function(req, res) {
    req.logout();
    res.redirect("/");
});

module.exports = router;

3 个答案:

答案 0 :(得分:2)

我无法看到您使用express.js

初始化passport.js的位置

您应该将其添加为中间件

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

那应该对你有所帮助。如果它没有帮助你,请看看这个例子。 alignment

答案 1 :(得分:1)

我不知道您的客户端如何通过正文或QS发送其数据......但是要从服务器端访问该信息,您需要执行以下操作:

req.body.user

req.user

使用NewsWebSite.BLL将始终为undef,因为请求对象没有此类属性。

答案 2 :(得分:0)

检查您是否支持代理。 如果代码中的所有内容都正确,并且您仍然遇到错误,那么您可能会在代理后面。 您可以通过第三方设置代理或在浏览器中设置代理来绕过代理!