我正在创建一个模块节点会话。我已经编写了用于在节点js中创建会话的简单代码。我使用了session.js文件,另一个是index.html文件。 我正在共享这两个文件代码,问题是当点击此URL http://localhost:8000/admin并单击登录链接然后再次重定向同一页面时,我不确定此内容中缺少什么。请帮助我!!!
session.js
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var app = express();
app.set('views', __dirname + '/view');
app.engine('html', require('ejs').renderFile);
app.use(session({ secret: 'ssshhhh', saveUninitialized: true, resave: true }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var sess;
app.get('/', function(req, res){
sess = req.session;
if(sess.email)
{
res.redirect('/admin');
} else {
res.render('index.html');
}
});
app.post('/login', function(req, res) {
sess = req.session;
sess.email = req.body.email;
res.end('done');
});
app.get('/admin', function (req, res){
sess = req.session;
if(sess.email)
{
res.write('<h1>Hello'+sess.email+'</h1><br>');
res.end('<a href='+'/logout'+'>Logout</a>');
}
else
{
res.write('<h1>Please login first.</h1>');
res.end('<a href='+'/'+'>Login</a>');
}
});
app.get('/logout', function(req,res){
req.session.destroy(function(err){
if(err)
{
console.log(err);
}
else
{
res.redirect('/')
}
});
});
app.listen(8000, function(){
console.log("App started on port 8000");
});
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function(){
var email, password;
$('#submit').click(function(){
email = $("#email").val();
password = $("#password").val();
});
$.post("http://localhost:8000/login", {
email: email,
password: password }, function(data){
if(data === 'done')
{
window.location.href = "/admin";
}
});
});
</script>
<body>
Email <input type="text" id="email" name=""><br>
Password <input type="password" id="password" name=""><br>
<input type="submit" id="submit">
</body>
</html>
答案 0 :(得分:0)
您的sess.email
未被破坏,因此发生了,请在登录前先单击注销链接,以便会话将被破坏,并且您的条件if(sess.email)
正常运行,我在<a href='+'/logput'+'>
中发现了第二个问题,请纠正它。
//change href from /logput to /logout
res.end('<a href='+'/logput'+'>Logout</a>');
>>
res.end('<a href='+'/logout'+'>Logout</a>');