简体   繁体   English

如何为每个页面生成一个随机数?

[英]How to generate a random number for each page?

I'm using node.js and express, and I'd like to generate a random five-figure number in app.js and return it to the client. 我正在使用node.js和express,我想在app.js中生成一个随机的五位数字并将其返回给客户端。

I'd like to do this on the server rather than the client, because I want to be certain that the number is different for every user who is currently connected . 我想在服务器而不是客户端上执行此操作,因为我想确定当前连接的每个用户的数量是不同的

Here's my current (broken) code from app.js: 这是我在app.js中的当前(损坏)代码:

// My first attempt - a function to generate a random number.
// But this returns the same number to every client. 
function genRandNum() {
    return Math.floor(Math.random() * 90000) + 10000;
}
// Routes
app.get('/', function(req, res){
  res.render('index', {
    title: 'Hello world',
    random_id: genRandNum() // No good - not different for each user. 
  });
});

There are actually two problems: 实际上有两个问题:

  1. How can I generate a number for each client? 如何为每个客户生成一个号码?
  2. How can I be certain the number is different for every client? 我如何确定每个客户的号码是否不同? Do I need to create a Redis store of currently open sessions and their numbers? 我是否需要创建当前打开的会话及其编号的Redis存储?

Thanks for helping out a beginner :) 感谢您帮助初学者:)

Your code works for me, with index.jade: 你的代码适用于我,index.jade:

h1 #{random_id}

However, as written it generates a random # for each page , not just each client. 但是,正如所写,它为每个页面生成一个随机#,而不仅仅是每个客户端。 Some sort of backing data store would be needed to permanently guarantee each client has a unique #, but since you're only using 5-digits (90K possible IDs), you're clearly not concerned with this being unguessable. 需要某种支持数据存储来永久保证每个客户端都有一个唯一的#,但由于你只使用5位数(90K可能的ID),你显然不关心这是不可思议的。 And if you only care about this in the context of a single node process, why not just use an auto incrementing value? 如果您只关注单个节点进程的上下文,为什么不使用自动递增值呢?

var clientId = 1;
app.get('/', function(req, res){
  res.render('index', {
    title: 'Hello world',
    random_id: clientId++ 
  });
});

对于唯一的随机数,您也可以从用户那里获得帮助..他可以输入一些随机的击键然后你可以修改它们/加/减一些东西并在服务器上发送

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

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