I'm currently working on a simple app with nodejs and express. I load a random number, the user translates that number to spanish, and user submits it. I then need to compare the user's answer with the actual translation to see if the user was correct.
The route for my main page is pretty simple: I render a layout with a random number for a user's given level in the game, along with a random noun (both are just functions that i've required from a separate file).
app.get('/', catchError(async (req, res) => {
res.render("layout", {
num: randNumForLevel(0),
noun: randNoun(),
});
}))
However, here's my challenge: when the user clicks "submit" I need to compare their answer with the actual spanish translation (in this case it's for the number "20"). However, the way I've currently structured the code, I generated the number and passed it directly into my view, which means I don't have access to it in the next request/response cycle.
So my question is this: where should I store this randomly generated number (in this case "20") so that I still have access to it when the user submits the form. Should I put it in the session? app.locals? somewhere else? Not sure what best practice is, so would love some advice.
CodePudding user response:
One simple solution that I can suggest is to send the number and the user response together to the server. When user submits you can send for example { number : 10, translation: 'diez' }
CodePudding user response:
The main problem with sending the actual translation and the randomly generated number is that the client can easily cheat and see the translation
I think you need to restructure the way you send the number.
Just as an example I'd use a database to store the numbers of level 1 with the following schema:
{ id: '1', number: 20, level: '1' }
You could always store these in memory as a JavaScript object and filter them by level.
const my_db = {
level1: [
{ id: '1', number: 10, level: '1', answer: 'diez' },
]
}
// create challenge programmatically
let randNum = randNumForLevel(0)
let noun = randNoun()
let answer = getTranslationFor(randNum)
my_db.level1.push({ id: '2', number: randNum, answer: answer })
Send the id of the challenge and the random number to the client. The response from the client should have the id of the challenge and the user translation.
Search the given id on your database or js object, compare the user translation and the correct translation and you're good to go
Nice! now you have a way to compare the numbers without sending the actual translation.