I got bored and decided to make a simple API in javascript. big mistake.
For some reason this very simple if/else statement will only run the code in if
, instead of else
. I have asked my friend who is more experienced in javascript than I am, but he can't see an issue either.
here is the code:
app.get("/number", (req, res) => {
const min = req.query.min || 0
const max = req.query.max || 100
if (min > max) {
res.status(400).json({
error: "min must be less than max. ur actually dumb"
})
} else {
const number = Math.floor(Math.random()*Math.max(min, max) Math.min(min, max))
res.json({
number: number,
"your ip LEAKED 2021 not clickbait!!!11!1": req.ip
})
}
})
here is the output:
so here I am, asking stack overflow to help me with an if statement. thank you
CodePudding user response:
min
and max
are strings since they're passed in as query arguments
You also don't need Math.min
or Math.max
since you already know which is bigger/smaller
Also use the ternary operators instead of ||
since if max is 0
, then max will be set to 100
app.get("/number", (req, res) => {
const min = isNaN(parseInt(req.query.min)) ? 0 : parseInt(req.query.min);
const max = isNaN(parseInt(req.query.max)) ? 100 : isNaN(parseInt(req.query.max));
if (min > max) {
res.status(400).json({
error: "min must be less than max. ur actually dumb"
});
} else {
const number = Math.floor(Math.random()*max min);
res.json({
number: number,
"your ip LEAKED 2021 not clickbait!!!11!1": req.ip
});
}
})
CodePudding user response:
you must parse req.query.min and req.query.max to integer otherwise, comparison won't work in the correct way
app.get("/number", (req, res) => {
const min = isNaN(parseInt(req.query.min)) ? 0 :
parseInt(req.query.min);
const max = isNaN(parseInt(req.query.max)) ? 100 :
parseInt(req.query.max);
if (min > max) {
res.status(400).json({
error: "min must be less than max. ur actually dumb"
});
} else {
const number = Math.floor(Math.random()*max min);
res.json({
number: number,
"your ip LEAKED 2021 not clickbait!!!11!1": req.ip
});
}
})