Express.js 的仅限会话 cookie

发布于 2024-10-06 04:52:12 字数 416 浏览 6 评论 0原文

http://www.javascriptkit.com/javatutors/cookie.shtml

另一方面,仅限会话 cookie 手,将信息存储在 浏览器内存,可用于 浏览器会话的持续时间。 换句话说,里面存储的数据 会话 cookie 可以从 存储时间直到浏览器 关闭。从一个页面移动到另一个页面 在此期间不会擦除 数据。

如何使用 Express.js 实现此目的?

http://www.javascriptkit.com/javatutors/cookie.shtml

Session-only cookies, on the other
hand, stores information in the
browser memory, and is available for
the duration of the browser session.
In other words, the data stored inside
a session cookie is available from the
time of storage until the browser is
closed. Moving from page to page
during this time does not erase the
data.

How can I achieve this using Express.js?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

暮光沉寂 2024-10-13 04:52:12

首先,该网站是一个可怕的地方。

现在回答问题。

会话实际上是什么:

  • 数据存储在服务器端。
  • 发出包含 ID 的 cookie。
  • 由于浏览器会发送 cookie,因此每次请求时该 ID 都会发送回服务器。
  • 现在,服务器可以将 cookie 中的 ID(通常称为Session ID 或简称 SID)与存储在服务器上的会话数据重新关联。

Express.js 支持内置会话

示例显示的内容:

  • 设置 Express.js 中间件
  • 使用第三方存储来保存会话数据,在本例中 Redis (IMO 对于你的问题 atm 来说是多余的)

安装 Redis 需要做很多工作,但也可以使用 Express.js 的内置内存存储:

var express = require('express');
var app = express.createServer();

var MemoryStore = require('connect/middleware/session/memory');
app.use(express.bodyDecoder());
app.use(express.cookieDecoder());
app.use(express.session({ store: new MemoryStore({ reapInterval: 60000 * 10 }) }));

app.get('/', function(req, res){
    req.session.visitCount = req.session.visitCount ? req.session.visitCount + 1 : 1;
    res.send('You have visited this page ' + req.session.visitCount + ' times');
});

app.listen(4000);

这将简单地记录您访问该页面、关闭浏览器并重新打开的次数。计数仍然存在。

您可以找到有关 MemoryStore 选项的更多信息,例如会话的最长生命周期等。此处

First off, that website is a horrible place to go.

Now on to the question.

What sessions actually are:

  • Data is stored on the server side.
  • A cookie is issued which contains an ID.
  • This ID gets send back to the server on every request, due to the fact that the browser sends the cookies.
  • Now the server can re-associate the ID in the cookie - commonly called Session ID or short SID - with the session data stored on the server.

Express.js has support for sessions built in.

What the example shows:

  • Setting up the Express.js middleware
  • Using a third-party store for saving the session data, in this case Redis (which IMO is overkill for your problem atm)

Installing Redis requires quite some work, but it's also possible to use Express.js's built-in memory store:

var express = require('express');
var app = express.createServer();

var MemoryStore = require('connect/middleware/session/memory');
app.use(express.bodyDecoder());
app.use(express.cookieDecoder());
app.use(express.session({ store: new MemoryStore({ reapInterval: 60000 * 10 }) }));

app.get('/', function(req, res){
    req.session.visitCount = req.session.visitCount ? req.session.visitCount + 1 : 1;
    res.send('You have visited this page ' + req.session.visitCount + ' times');
});

app.listen(4000);

This will simply keep track of how many times you visited the page, closed your browser and re-opend. The counts will still be there.

You can find more on the options of the MemoryStore, like maximum life time of a session, etc. here.

情话难免假 2024-10-13 04:52:12

以下是我想要的(某种程度上)。当我关闭浏览器时,信息就消失了。

var express = require('express');
var app = express.createServer();

var MemoryStore = require('connect/middleware/session/memory');
app.use(express.bodyDecoder());
app.use(express.cookieDecoder());

app.get('/remember', function(req, res) {
    res.cookie('rememberme', 'yes', { expires: new Date() - 1, httpOnly: true });
});

app.get('/', function(req, res){
    res.send('remember: ' + req.cookies.rememberme);
});

app.listen(4000, '127.0.0.1');

The following is what I wanted (sort of). When I close browser the information is gone.

var express = require('express');
var app = express.createServer();

var MemoryStore = require('connect/middleware/session/memory');
app.use(express.bodyDecoder());
app.use(express.cookieDecoder());

app.get('/remember', function(req, res) {
    res.cookie('rememberme', 'yes', { expires: new Date() - 1, httpOnly: true });
});

app.get('/', function(req, res){
    res.send('remember: ' + req.cookies.rememberme);
});

app.listen(4000, '127.0.0.1');
走走停停 2024-10-13 04:52:12
app.use(express.session({cookie: { path: '/', httpOnly: true, maxAge: null }, secret:'eeuqram'}));

以上适用于 IE8、Firefox 和 Chrome。
重要的部分是 ma​​xAge:null

app.use(express.session({cookie: { path: '/', httpOnly: true, maxAge: null }, secret:'eeuqram'}));

The above works on IE8, Firefox and Chrome.
The important piece is maxAge:null

森罗 2024-10-13 04:52:12
app.get('/remember', function(req, res) {
   res.cookie('rememberme', 'yes', { expires: 0, httpOnly: true });
 });

这将设置会话 cookie。浏览器关闭时它将被删除!

app.get('/remember', function(req, res) {
   res.cookie('rememberme', 'yes', { expires: 0, httpOnly: true });
 });

This will set session cookie. On browser close it will be erased!

韬韬不绝 2024-10-13 04:52:12

下面是 Alfred 的回答(使用 Express 的会话)的更新代码.js)。

    var express = require('express');
    var app = express.createServer();

    var MemoryStore = require('/home/node/node_modules/connect/lib/middleware/session/memory');
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.session({
        key: 'some-key',
        secret: 'some-We1rD sEEEEEcret!',
        store: new MemoryStore({ reapInterval: 60000 * 10 })
    }));

   app.get('/', function(req, res) {
       req.session.visitCount = req.session.visitCount ? req.session.visitCount + 1 : 1;
       res.send('You have visited this page ' + req.session.visitCount + ' times');
   });

   app.listen(4000);

Below is the updated code for Alfred's answer (session using Express.js).

    var express = require('express');
    var app = express.createServer();

    var MemoryStore = require('/home/node/node_modules/connect/lib/middleware/session/memory');
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.session({
        key: 'some-key',
        secret: 'some-We1rD sEEEEEcret!',
        store: new MemoryStore({ reapInterval: 60000 * 10 })
    }));

   app.get('/', function(req, res) {
       req.session.visitCount = req.session.visitCount ? req.session.visitCount + 1 : 1;
       res.send('You have visited this page ' + req.session.visitCount + ' times');
   });

   app.listen(4000);
指尖微凉心微凉 2024-10-13 04:52:12

我知道这是一个老问题,但我添加了一个答案,因为这里的所有答案似乎都已过时、存在安全缺陷或完全错误。

截至目前,express 默认使用 MemoryStore,您不需要显式处理它。

此外,截至目前,express-session 的 官方自述文件页面 有一个严厉警告:开始不使用 MemoryStore 作为生产的会话存储,引用:

警告默认的服务器端会话存储 MemoryStore 并不是专门为生产环境设计的。它在大多数情况下都会泄漏内存,无法扩展超过单个进程,并且用于调试和开发。
有关存储区列表,请参阅兼容的会话存储区。< /p>

如果您想使用 MongoDBStore 进行会话存储,这里有一个使用 connect-mongodb-session 的简单解决方案:

import express from 'express';
import session from 'express-session';
import ConnectMongoDbSession from 'connect-mongodb-session';

const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(session({
  secret: < COOKIE_SECRET >,
  name: 'sessionId', // Don't use the default name, see http://expressjs.com/en/advanced/best-practice-security.html
  cookie: {
    httpOnly: true,
    secure: true, // Remove this if you're not using HTTPS, but it will be a massive security flaw
    sameSite: 'strict',
  },
  store: getStore(),

  // Boilerplate options, see:
  // * https://www.npmjs.com/package/express-session#resave
  // * https://www.npmjs.com/package/express-session#saveuninitialized
  resave: true,
  saveUninitialized: true,
}));

function getStore() {
  const MongoDBStore = ConnectMongoDbSession(session);

  const store = new MongoDBStore({
    uri: < DATABASE_URI >,
    collection: < SESSION_COLLECTION_NAME >,
    connectionOptions: {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    },
  });

  store.on('error', (error: any) => {
    console.error(error);
  });

  return store;
}

I know this is an old question but I'm adding an answer since all answers here seem to be either outdated, have security flaws or are just plain wrong.

As of now, express uses the MemoryStore by default, you don't need to explicitly handle that.

Also, as of now, the express-session's official readme page has a stark warning at the beginning to not use MemoryStore as the session store for production, quoting:

Warning The default server-side session storage, MemoryStore, is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing.
For a list of stores, see compatible session stores.

Here's a simple solution with connect-mongodb-session if you want to use MongoDBStore for session storage:

import express from 'express';
import session from 'express-session';
import ConnectMongoDbSession from 'connect-mongodb-session';

const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(session({
  secret: < COOKIE_SECRET >,
  name: 'sessionId', // Don't use the default name, see http://expressjs.com/en/advanced/best-practice-security.html
  cookie: {
    httpOnly: true,
    secure: true, // Remove this if you're not using HTTPS, but it will be a massive security flaw
    sameSite: 'strict',
  },
  store: getStore(),

  // Boilerplate options, see:
  // * https://www.npmjs.com/package/express-session#resave
  // * https://www.npmjs.com/package/express-session#saveuninitialized
  resave: true,
  saveUninitialized: true,
}));

function getStore() {
  const MongoDBStore = ConnectMongoDbSession(session);

  const store = new MongoDBStore({
    uri: < DATABASE_URI >,
    collection: < SESSION_COLLECTION_NAME >,
    connectionOptions: {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    },
  });

  store.on('error', (error: any) => {
    console.error(error);
  });

  return store;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文