Search code examples
javascriptresthttpgetmodule-export

export input query from one GET request and use them on separate requests


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!


Solution

  • 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