Ric*_*ard 6 javascript node.js express
我正在使用node.js和express,我想在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.
});
});
Run Code Online (Sandbox Code Playgroud)
实际上有两个问题:
感谢您帮助初学者:)
你的代码对我有用,使用index.jade:
h1 #{random_id}
Run Code Online (Sandbox Code Playgroud)
然而,正如所写,它会为每个页面生成一个随机的# ,而不仅仅是每个客户端。需要某种类型的后备数据存储来永久保证每个客户端都有一个唯一的#,但由于您只使用 5 位数字(90K 可能的 ID),因此您显然不担心这是不可猜测的。如果您只在单节点进程的上下文中关心这一点,为什么不只使用自动递增值呢?
var clientId = 1;
app.get('/', function(req, res){
res.render('index', {
title: 'Hello world',
random_id: clientId++
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4006 次 |
| 最近记录: |