Reputation: 15
I am trying to use the input of the user on my RESTful API
in the query for one GET
request and use that data to randomize a number and use that info for the rest of the application. any guidance about best solution to store the values and use them on different blocks throughout the application is appreciated.
Part of the code sample is as below:
app.get("/start", (req, res) => {
const numberOfFigures = req.query.figures;
const randomBaseNumber = Math.random();
const theNumber = (randomBaseNumber * 10 ** numberOfFigures).toFixed(0);
res.send(`guess the ${numberOfFigures} digit number!`);
app.get("/guess", (req, res) => {
let guessedNumber = req.query.guess;
if (guessedNumber !== theNumber) {
console.log("Wrong! Guess again");
}
I am trying to use for instance theNumber value from /Start request in the /guess request!
Upvotes: 0
Views: 63
Reputation: 51
The following 3 ways of storing data come to mind:
Method 1 is the easiest way. The variable will be accessible from all the routes, and it will be erased if your app restarts.
let theNumber = 0;
...
app.get("/start", (req, res) => {
theNumber = ...
...
Methods 2 and 3 will make the variable, once created, persist even if the app restarts. However, for this simple use case, I'd say they're overkill.
Upvotes: 0
Reputation: 2261
You need to keep theNumber
variable outside of the scope of both callbacks e.g.
let theNumber = 0
app.get("/start", (req, res) => {
const numberOfFigures = req.query.figures;
const randomBaseNumber = Math.random();
theNumber = (randomBaseNumber * 10 ** numberOfFigures).toFixed(0);
res.send(`guess the ${numberOfFigures} digit number!`);
app.get("/guess", (req, res) => {
let guessedNumber = req.query.guess;
if (guessedNumber !== theNumber) {
console.log("Wrong! Guess again");
}
I would also use POST for the /guess
endpoint
Upvotes: 0