繁体   English   中英

NodeJs Express会话管理

[英]NodeJs Express Session Management

我在这里有这个问题,我一直在尝试在Internet上甚至在Stackoverflow上进行搜索,但是我没有得到所需的确切解决方案。 我正在创建一个由基本身份验证驱动的应用程序,其中要求用户登录时登录我想要sendFile()它们将是主页,我希望在主页上能够检查是否设置了会话如果没有,则使用NodeJS,Javascript和Express重定向到登录。

如果是在PHP上,则与此类似:

session_start();
if(!isset($_SESSION['user_id'])
     location('header: login.php')
<html>
      <?php
         echo "Your user id is: ".user_id;
      ?>
</html>

基本上,我想在会话中设置id并能够在主页/其他页面中读取它,而不仅在服务器上也可以在home.html中进行。

您可能不想使用sendFile,而是想使用res.redirect将用户发送到另一个端点。 例如,此端点可能是您的主页,但是通常最好使用适当的快速呈现而不是sendFile,除非您尝试执行让用户下载blob文件的操作。

您可以设置一个端点,例如:

const express = require('express');
const app = express();

// setup render system here...

app.use('/', (req, res) => {
    res.render('home');
});

这将在主模板上调用渲染。 要设置模板引擎,您可以使用express-hbs或其他渲染引擎。 这些将允许您在返回值之前将值注入HTML中,如果您希望添加错误消息,这可能会很有用。

配置完成后,您可以创建一个名为home.hbs之类的模板(位置和扩展名取决于您的库和设置)。

然后,您可以使用express-session检查会话。

app.use('/secured', (req, res) => {
    if (req.session) {
        // We have a session! Now you can validate it to check it's a good session
    } else {
        // No session at all, redirect them to the home screen.
        // You might want to make this the login screen instead.
        res.redirect('/');
    }
});

一些最终的演示代码可能看起来像这样

const express = require('express');
const app = express();

// Setup express session...
const session = require('express-session');

app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
}));

// Setup the vie engine...
var hbs = require('express-hbs');

// Use `.hbs` for extensions and find partials in `views/partials`.
app.engine('hbs', hbs.express4({
  partialsDir: __dirname + '/views/partials'
}));
app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');

// Place a file called `views/home.hbs` in the views folder at the top level of your project.
// Fill it with some html, all html is valid, handlebars just adds additional features for you.

// A public route which requires no session
app.use('/', (req, res) => {
    // Renders "views/home.hbs"
    res.render('home');
});

// A secured route that requires a session
app.use('/secured', (req, res) => {
    if (req.session) {
        // We have a session! Now you can validate it to check it's a good session
    } else {
        // No session at all, redirect them to the home screen.
        // You might want to make this the login screen instead.
        res.redirect('/');
    }
});

请注意,我实际上并未运行此代码,因此可能存在一些语法错误等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM