How to create a random number for each page?

I use node.js and express, and I would like to create a random five-digit number in app.js and return it to the client.

I would like to do this on the server, and not on the client, because I want to be sure that this number is different for each user who is currently connected .

Here is my current (broken) code from 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:

  • How can I generate a number for each client?
  • How can I be sure that the number is different for each client? Do I need to create a Redis repository for open sessions and their numbers?

Thanks for the help to the beginner :)

+6
source share
2 answers

Your code works for me, with index.jade:

 h1 #{random_id} 

However, as it is written, it generates a random # for each page, and not just for each client. You will need some kind of backup data storage to ensure that each client has a unique number # forever, but since you use only 5 digits (90 KB of possible identifiers), you are clearly not worried that this is not possible. And if you only care about this in the context of a single node process, why not just use the auto-increment value?

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

For unique random numbers, you can also get help from your user .. he can enter random keystrokes, and then you can change / add / subtract them and send them to the server

0
source

Source: https://habr.com/ru/post/898206/


All Articles