NodeJs快速会话管理

问题描述 投票:0回答:1

我在这里有这个问题,我一直试图在互联网上搜索,甚至在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中执行此操作。

javascript node.js express session
1个回答
0
投票

您可能不想使用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的模板(位置和扩展名取决于您的库和设置)。

然后,您可以使用快速会话来检查会话。

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('/');
    }
});

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

© www.soinside.com 2019 - 2024. All rights reserved.