Reputation: 1195
I am trying to create a session variable (loggedin) if the user log in, but I get TypeError: Cannot set property 'loggedin' of undefined
. I can't figure out why it does not work. I have tried to reinstall session records and alsp change place for it in the code but still the same error. Any idea why I get this error?
Here is the code:
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;
Upvotes: 0
Views: 2277
Reputation: 1362
You're exporting the router, which should be the app.
So app
has access to all middleware, router6
doesn't.
router6
is an instance of app
. You ask the app
instance to use session. But you actually export the router.
So module.exports = app;
should fix this.
Upvotes: 2