O
O
olmax042021-04-03 16:58:24
Express.js
olmax04, 2021-04-03 16:58:24

Puppeteer, expressjs, JavaScript. How to pass a variable from 1 function to another?

I am writing a function that will receive the page (and browser) variable in 1 function, using callback to transfer it to another function. At the moment, I have settled on the problem of its transfer, since it will not work to set a global variable (this will violate my further plan related to the multithreading of the application). If anyone knows - help, how can I do this?

router.post(
  '/check',
  [check('user_login', 'Некорректный логин').isLength({ min: 3 })],
  async function checkdata(req, res) {
    try {
      console.log('Login body:', req.body);
        let browser = await puppeteer.launch({
          devtools:true,
        });
        let page = await browser.newPage()
        await page.goto('https://google.com')
        await page.type('input[name=q]',req.body.user_login)
        await page.screenshot({path:'loximi.png'})
        res.json({ message: 'completed' });
        return new Promise (async (resolve)=>{
          resolve(page);
        })
    } catch (e) {
      console.log(e.message);
      res
        .status(500)
        .json({ message: 'Что-то пошло не так, попробуйте снова' });
    }
  }
);

// /api/auth/register
router.post(
  '/register',
  [
    check('user_login', 'Некорректный логин').isLength({ min: 3 }),
    check('user_password', 'Минимальная длина пароля 6 символов').isLength({
      min: 6,
    }),
  ],
  async (req, res) => {
    try {
      console.log('Password body:', req.body);
      console.log(checkdata())
      await page.type('input[name=q]', checkdata())
      res.json({ message: 'completed' });


    } catch (e) {
      console.log(e.message);
      res
        .status(500)
        .json({ message: 'Что-то пошло не так, попробуйте снова' });
    }
  }
);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
olmax04, 2021-04-04
@olmax04

Everything turned out to be easier. Made a binding to the session by creating a hash.
var createHash = require('hash-generator');
let session = createHash(12);
And then I set the variables in the post requests themselves, which will be used in the routes.
//set variable
app.set(`login_${session}`, user_login);
//call it in other routes
app.get(`login_${session}`);
I pass the session variable through react to each route, and thus everything works

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question