首页 > 解决方案 > 节点 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>

标签: node.js

解决方案


推荐阅读