nodejs身份验证系统中的“ TypeError:无法读取未定义的属性'email'”

时间:2019-05-27 06:39:38

标签: node.js express passport.js node-redis

我正在尝试使用快速会话和通行证运行身份验证模块。

server.js

var express = require("express");
var session = require('express-session'); 
var connection = require('./config');
var bodyParser = require('body-parser');
var passport = require('passport');
const redis = require('redis');
const redisStore = require('connect-redis')(session);
const client  = redis.createClient();
var app = express();
var router = express.Router();
var authController=require('./controllers/auth-controller');
var regController=require('./controllers/reg-controller');

app.use(session({secret: 'secret', store: new redisStore({ host: 'localhost', port: 8000, client: client,ttl : 260}), saveUninitialized: true, resave: true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

router.get('/',(req,res) => {
    let sess = req.session;
    if(sess.email){
        return res.redirect('/admin');
    }
    res.sendFile( __dirname + '/' + 'index.html' );
})

router.post('/login',(req,res) => {
    sess = req.session;
    sess.email = req.body.email;
    res.end('done');
});

router.get('/admin',(req,res) => {
    sess = req.session;
    if(sess.email) {
        res.write(`<h1>Hello ${sess.email} </h1><br>`);
        res.end('<a href='+'/logout'+'>Logout</a>');
    }
    else {
        res.write('<h1>Please login first.</h1>');
        res.end('<a href='+'/'+'>Login</a>');
    }
});

router.get('/logout',(req,res) => {
    req.session.destroy((err) => {
        if(err) {
            return console.log(err);
        }
        res.redirect('/');
    });

});

app.use('/', router);

app.post('/api/register',regController.register);
app.post('/api/authenticate',authController.authenticate);

console.log(authController);
app.post('/controllers/register-controller', regController.register);
app.post('/controllers/authenticate-controller', authController.authenticate);
app.listen(8000);

config.js

var mysql      = require('mysql');
const localAuth = require('./controllers/timeoutcontroller');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'password',
  database : 'dbname'
});
connection.connect(function(err){
if(!err) {
    console.log("Database is connected");
} else {
    console.log("Error while connecting with database");
}
});

function ensureAuthenticated(req, res, next) {
  if (!(req.headers && req.headers.authorization)) {
    return res.status(400).json({
      status: 'Please log in'
    });
  }
  // decode the token
  var header = req.headers.authorization.split(' ');
  var token = header[1];
  localAuth.decodeToken(token, (err, payload) => {
    if (err) {
      return res.status(401).json({
        status: 'Token has expired'
      });
    } else {
      return knex('users').where({id: parseInt(payload.sub)}).first()
      .then((user) => {
        next();
      })
      .catch((err) => {
        res.status(500).json({
          status: 'error'
        });
      });
    }
  });
}

module.exports = connection; 

在这里,我能够连接到mysql数据库并设置了连接,但出现错误

TypeError:无法读取未定义的属性“电子邮件”

如果有人可以解释为什么会这样,那就太好了。 谢谢。

1 个答案:

答案 0 :(得分:0)

这意味着您的变量sess未定义。您的req.session变量内部没有任何值。您需要检查为什么会这样。

尝试一下:

let sess = req.session;
sess.user = req.user;
req.mysess=sess.user //pass like this


router.get('/', function(req, res, next) {
    let sess = req.mysess;
    console.log(sess);
});