简体   繁体   English

NodeJs Express会话管理

[英]NodeJs Express Session Management

I have this question here, I have been trying to search around the internet and even here on Stackoverflow but I am not getting the exact solution I need. 我在这里有这个问题,我一直在尝试在Internet上甚至在Stackoverflow上进行搜索,但是我没有得到所需的确切解决方案。 I am creating some application that is driven by a basic authentication where user is required to login the when they are logged in I want to sendFile() them which will be home page I want on home page to be able to check if session are set then if not then redirect to login using NodeJS, Javascript, as well as Express. 我正在创建一个由基本身份验证驱动的应用程序,其中要求用户登录时登录我想要sendFile()它们将是主页,我希望在主页上能够检查是否设置了会话如果没有,则使用NodeJS,Javascript和Express重定向到登录。

This if it was on PHP was to be similar to this: 如果是在PHP上,则与此类似:

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

Basically I want to set in the session on id and be able to read it in home page/other pages without doing this on only the server but also in home.html. 基本上,我想在会话中设置id并能够在主页/其他页面中读取它,而不仅在服务器上也可以在home.html中进行。

You probably don't want to use sendFile, instead you probably want to use res.redirect, to send the user to a different endpoint. 您可能不想使用sendFile,而是想使用res.redirect将用户发送到另一个端点。 This endpoint could be your home page for example, but it's generally a better to use proper express rendering rather than sendFile unless you're trying to do something like letting the user download a blob file. 例如,此端点可能是您的主页,但是通常最好使用适当的快速呈现而不是sendFile,除非您尝试执行让用户下载blob文件的操作。

You could setup an endpoint such as: 您可以设置一个端点,例如:

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

// setup render system here...

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

This will call the render on the home template. 这将在主模板上调用渲染。 To setup a templating engine, you can use something like express-hbs or other rendering engines. 要设置模板引擎,您可以使用express-hbs或其他渲染引擎。 These will allow you to inject values into the HTML before returning it, which might be useful if you wish to add an error message. 这些将允许您在返回值之前将值注入HTML中,如果您希望添加错误消息,这可能会很有用。

Once that's configured you can create a template called something like home.hbs (the location and extension will depend on your library and settings). 配置完成后,您可以创建一个名为home.hbs之类的模板(位置和扩展名取决于您的库和设置)。

You can then use express-session to check for a session. 然后,您可以使用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('/');
    }
});

Some final demo code might look like this 一些最终的演示代码可能看起来像这样

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

Note, I've not actually run this code, so there may be a few syntax errors and such. 请注意,我实际上并未运行此代码,因此可能存在一些语法错误等。

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

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