Noob在这里,我试图建立一个会话来进行nodejs中的登录尝试计数,但是似乎该会话未在route中声明,因为它在我console.log时显示为未定义。
下面是我的代码:
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);
});
在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;
我尝试将计数存储在user.js的req.session [email]中,并在计数等于3时阻止电子邮件。但是,每次尝试登录哪个错误时,它都不存储计数并显示未定义密码。
非常感谢您的建议。
答案 0 :(得分:1)
将这些行添加到顶部:
app.use(express.json())
app.use(express.urlencoded({ extended: true }))