Ask coding questions

← Back to all posts
How to send a random response?
h
AngelHeart1 (0)

So 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"}. unless I restart the repl. How do i stop that or how do I make it send a random response, thanks :)

Answered by EpicGamer007 (1728) [earned 5 cycles]
View Answer
Comments
hotnewtop
AloegelhiPlaysR (129)

Try using this:

let x = setInterval(function() => {
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const randomMonth = months[Math.floor(Math.random() * months.length)];
}, 1000) //Every 1 second
app.get('/v1/month', (req, res) => {
    res.json({ month: x })
});
AngelHeart1 (0)

its fine i worked it out, thanks though :) @AloegelhiPlaysR

EpicGamer007 (1728)

@AngelHeart1 you should have put the const randomMonth = months[Math.floor(Math.random() * months.length)]; into the app.get().