如何在Node.js中生成会话ID?

use*_*794 5 cookies uniqueidentifier unique-key node.js

我试图在不使用任何第三方模块或框架的情况下学习Node.js。我现在要弄清楚如何为登录的用户提供会话ID ...

到目前为止,我知道我可以通过将其写在标题中并设置cookie来设置会话ID:

writeHead(200, {'set-cookie':'Math.random() ' } );
Run Code Online (Sandbox Code Playgroud)

然后我可以检索会话ID,然后将其与数据库进行比较。

request.headers.cookie(request.url);
Run Code Online (Sandbox Code Playgroud)

但是,如何生成会话ID值?我是编程新手。我想到的第一件事是使用Javascript的 Math.random();。并使用该值设置Cookie(会话ID)。在我看来,这很愚蠢,但这就是我能想到的。

我想如何使用Node.js生成会话ID,请不要使用任何第三方模块,准系统!

Tra*_*er1 5

注意:您可能应该为您使用的任何框架使用会话管理器......无论是 connect、express、koa 还是任何其他框架。


这将为您提供一个UUID 版本 4(随机),使用crypto.randomBytes.

var crypto = require('crypto');
module.exports = genUuid;

function genUuid(callback) {
  if (typeof(callback) !== 'function') {
    return uuidFromBytes(crypto.randomBytes(16));
  }

  crypto.randomBytes(16, function(err, rnd) {
    if (err) return callback(err);
    callback(null, uuidFromBytes(rnd));
  });
}

function uuidFromBytes(rnd) {
  rnd[6] = (rnd[6] & 0x0f) | 0x40;
  rnd[8] = (rnd[8] & 0x3f) | 0x80;
  rnd = rnd.toString('hex').match(/(.{8})(.{4})(.{4})(.{4})(.{12})/);
  rnd.shift();
  return rnd.join('-');
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用npm 中的UUID 模块尽管您可以使用Browserify 的 crypto shim,但 crypto 包不是浏览器内选项。