node.js - 节点 JS 会话代码无法在同一页面再次重定向
问题描述
我正在创建一个模块节点会话。我已经为在节点 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");
});
索引.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>
解决方案
推荐阅读
- python - Django CreateView在提交后不保存和加载成功的url
- python - 如何下载额外的python模块
- c++ - 是否可以将整个映射或对象指针数组从子类转换为基类?
- java - 如何在java中使用while循环生成随机数?
- python - implement a custom open() function / 'subclass' the open() function
- javascript - JavaScript 似乎存储了我不想存储的答案
- java - Google FooBar Code Running in IDE but failing all test cases
- android - java.lang.IllegalStateException: Fragment already added exception for BottomSheetDialogFragment
- linux - Linux:将文本填充到固定长度
- karate - 是否有将来自多个项目的 karate-config.js 文件合并到一个空手道文件中的功能?