问题
Noob here, and I tried to have a session to do the login attempt count in nodejs, but it seem the session is not declared in route as it just show undefined when i console.log it.
Below is my code :
Server.js
var express = require('express');
var session = require('express-session');
var cors = require('cors');
var bodyParser = require("body-parser");
var app = express();
var port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(cors());
app.use(session({ resave: false, saveUninitialized: true, secret: 'onemonkey', cookie: { secure: false }}));
app.use(bodyParser.urlencoded({
extended: false
}));
var Users = require('./Routes/Users');
app.use('/users',Users);
app.listen(port,function(){
console.log("Server is running on port: "+port);
});
in users.js
var express = require('express');
var users = express.Router();
var database = require('../Database/database');
var cors = require('cors')
var jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
//var request = require('request');
var token;
users.use(cors());
users.post('/login', function(req, res) {
var appData = {};
var email = req.body.email;
var password = req.body.password;
let someRows, otherRows;
let token;
var databaseQuery = new database.DatabaseQuery();
databaseQuery.beginTransaction()
.then (() => {
return databaseQuery.query('SELECT * FROM users WHERE email = ? AND status = ?', [email, 'active'])
})
.then( rows => {
someRows = rows;
if (someRows.length > 0) {
bcrypt.compare(password, someRows[0].password).then(function(ret) {
// res == true
if(ret){
//when validate successfully
}else{
console.log(req.session[email]);
req.session[email] = req.session[email] + 1;
req.session.save();
console.log('--------login-----');
console.log(req.session[email]);
if(req.session[email] == 3){
databaseQuery.query('update users set status=? where email=?',['block',email])
.then( rows => {
otherRows = rows;
var user_status = {
contact_id : someRows.insertId,
remark : "3 times login attempt fail",
status : "block",
edit_by : "SYSTEM"
}
return databaseQuery.query( 'INSERT INTO user_status_detail SET ?', [user_status] );
}).then ( rows =>{
appData.error = 1;
appData["data"] = "Email account blocked";
req.session[email] = null;
req.session.save();
res.status(200).json(appData);
return databaseQuery.commit();
}, err => {
return databaseQuery.close.then( () => { throw err; } )
})
}else{
//record not match
}
}
});
}else {
//account not exist
}
})
.catch( err => {
//err handling
} )
});
module.exports = users;
I tried to store the count in req.session[email] in user.js, and block the email once the count equal to 3. However, it not storing the count and showing undefined every time i tried to login which wrong password.
Highly appreciate your advise on it.
回答1:
add these lines to the top :
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
来源:https://stackoverflow.com/questions/53943457/get-undefined-for-req-session-in-nodejs