Problem description: Use express session
to implement a login page. When using app.post
to process the form, the judgment statement
if(req.body.password!=user[req.body.user].password||!user[req.body.user])
Among them, json
file content is:
{
"baidu":{
"password":"123",
"name":"百度"
}
}
There is a problem, the specific manifestation is:
The username and password are placed in a json
file and processed in app.js
. When testing, if the username and password are correct, then It runs normally; however, if the username and password are incorrect, it displays:
TypeError: Cannot read property 'password' of undefined
I checked the information and consulted on overflow
but I didn’t get a definite answer.
Are there any experts in this field who can provide some solutions?
The following is the code of app.js
:
var express = require('express');
var user = require('./user');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var multer = require('multer');
var session = require('express-session');
var path = require('path');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(session({
secret: 'baiduApp',
cookie: {maxAge: 60 * 1000 * 30},
resave: true,
saveUninitialized: false
}));
app.get('/', function (req, res) {
if (req.session.sign) {
console.log(req.session);
res.render('sign', {session: req.session})
} else {
res.render('index', {title: 'index'})
}
});
app.get('/out', function (req, res) {
req.session.destroy();
res.redirect('/');
});
app.post('/sign', function (req, res) {
//登录的数据和user.json中的数据进行对比
if (req.body.password != user[req.body.user].password || !user[req.body.user]) {
res.end('sign failure');
} else {
req.session.sign = true;
req.session.name = user[req.body.user].name;
res.send('welecome <strong>' + req.session.name + '</strong>,<a href="/out">登出</a>');
}
});
app.listen(80);
The judgment here is written backwards
It should be:
First you have to determine whether there is
req.body.user
this attribute in json.I found another solution to this problem:
You should first determine whether you have an account, otherwise you will get
cannot read property password of undefined
Error:Combined with the previous reverse thinking, both solutions can solve this problem well.