user15441631
user15441631

Reputation: 9

How to send a random value in Node.js or express.js

I had this express.js code. As shown below:

const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const randomMonth = months[Math.floor(Math.random() * months.length)];

app.get('/v1/month', (req, res) => {
    res.json({ month: randomMonth })
});

But what happens is I always get the same response which is {"month":"July"}.

How do I make it send a random response?

Upvotes: 0

Views: 1476

Answers (4)

charmful0x
charmful0x

Reputation: 153

you can use rando-js instead: https://www.npmjs.com/package/rando-js

const rando = require("rando-js")
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

const randoMonth = rando.fromArray(months)

Upvotes: 0

Kayes Fahim
Kayes Fahim

Reputation: 690

    const months = ["January", "February", "March", "April", "May", "June", 
              "July", "August", "September", "October", "November",  "December"];
    const randomMonth = months[Math.floor(Math.random() * (months.length - 1)) + 1];

 app.get('/v1/month', (req, res) => {
 res.json({ month: randomMonth })
 });

Upvotes: 0

manish
manish

Reputation: 1

try this to generate random number

const randomMonth = months[Math.floor(Math.random() * (months.length - 1)) + 1];

Upvotes: 0

Daniel Tran
Daniel Tran

Reputation: 6171

Because the month has been calculated upfront.

What you need to do is, having the same code called in the routing function.


const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];


app.get('/v1/month', (req, res) => {
    const randomMonth = months[Math.floor(Math.random() * months.length)];
    res.json({ month: randomMonth })
});

Upvotes: 1

Related Questions