nodeJS + Express-Session错误:无法设置未定义的属性“ loggedin”

时间:2019-11-14 21:00:34

标签: node.js session-variables

如果用户登录,我试图创建一个会话变量(登录),但是得到TypeError: Cannot set property 'loggedin' of undefined。我不知道为什么它不起作用。我试图重新安装会话记录,并在代码中为其更改位置,但仍然是相同的错误。知道为什么我会收到此错误吗?

代码如下:

   var mysql = require('mysql');
    var express = require('express'); 
    var session = require('express-session'); 
    var bodyParser = require('body-parser'); 
    var path = require('path');
    var app = express();

    var connection = mysql.createConnection({
            host     : 'localhost',
            user     : 'root',
            password : 'password',
            database : 'database'
        });

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

app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());

const router6 = express.Router();

app.use('/static', express.static(path.join(__dirname + '/public'))); 

router6.get('/login', function(request, response) {
response.sendFile(path.join(__dirname + '/login.html'));
}); 


//*** SESSION VARIABLE SET BELOW ***// 
//Post for authentication, from form action

router6.post('/authThis', function(request, response) { 
   let username = request.body.username; 
   let password = request.body.password;
   console.log(username + password)

   if (username && password) { 
   connection.query('SELECT * FROM users WHERE username = ? AND password = ?', [username, password], function(error, results, fields) { 
        if (results.length > 0) { 
            request.session.loggedin = true; //Error here. Says cannot set loggedin property
            request.session.username = username; 
            response.redirect('/');
            } else {
                    response.send('Incorrect Username and/or Password!'); 
                }           
                response.end();
            });
        } else {
            response.send('Please enter Username and Password!'); //om anv & lös inte fyllts i.
            response.end();
        }
        });


//******
        module.exports = router6;

1 个答案:

答案 0 :(得分:2)

您正在导出路由器,应该是应用程序。

因此app可以访问所有中间件,而router6没有访问权。

router6app的实例。您要求app实例使用会话。但是实际上是导出路由器。

因此module.exports = app;应该解决此问题。