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

Posted

技术标签:

【中文标题】尝试访问节点 js 中的 req.user 属性时无法读取未定义的属性“用户名”【英文标题】:Cannot read property 'username' of undefined while trying to access the req.user property in node js 【发布时间】:2017-05-21 08:39:58 【问题描述】:

我正在使用平均堆栈。我想访问 req.user 属性。但是当我尝试显示当前用户的用户名时,我收到一条错误消息,提示 Cannot read property 'username' of undefined。我参考了一些网站。 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;

【问题讨论】:

erm...请更新此帖子,以便代码位于代码块中。 【参考方案1】:

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

req.params.user 

req.body.user

使用req.user 将始终是 undef,因为请求对象没有这样的属性。

【讨论】:

【参考方案2】:

我看不到你在哪里用 express.js 初始化了你的 passport.js

你应该把它添加为中间件

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

这应该对你有帮助。如果它对您没有帮助,请查看此示例。 https://blog.risingstack.com/node-hero-node-js-authentication-passport-js/

【讨论】:

知道了,让我们创建其他文件,例如命名为passport.js 将所有策略和配置放入该文件,并从该文件中导出passport.js。最后在app.js 中,导入该文件而不是导入实际的 passport.js【参考方案3】:

检查您是否在代理后面。 如果代码中的一切都正确,并且您仍然收到错误,则您可能在代理后面。 您可以通过第三方设置代理或在浏览器中设置来绕过代理!

【讨论】:

以上是关于尝试访问节点 js 中的 req.user 属性时无法读取未定义的属性“用户名”的主要内容,如果未能解决你的问题,请参考以下文章

无法使用 Passport.js 和 Express 4 访问 req.user

req.user 未定义 - 节点 + 快递 + 护照-facebook

Passport JS req.user 未定义

如何告诉 Passport JS 中的 typescript req.user 永远不会被定义?

Passport.js、会话和反应 |从 /login 路由以外的任何路由访问 req.user 是未定义的

将 req.user 传递给 graphQL