Reputation: 9
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
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
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
Reputation: 1
try this to generate random number
const randomMonth = months[Math.floor(Math.random() * (months.length - 1)) + 1];
Upvotes: 0
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