Error: Evaluation failed: ReferenceError: req is not defined

Viewed 4005

I have an express setup. For some reason req is not being recognized in this function:

router.post('/search', (req, res) => {
  ;(async (req, res) => { //req and res here are just parameters in function definition
    const browser = await puppeteer.launch()
    const page = await browser.newPage()
    await page.goto(`https://www.google.com/search?tbm=bks&q=%22this+is%22`)
    const result = await page.evaluate(() => {
      console.log('CLAUSESS:', req.body.clauses)
      const clauses = req.body.clauses
      return clauses.map(clause => clause.textContent)
    })
    result.join('\n')
    await browser.close()
    res.send(result)
  })(req,res); //This is where we call the function, so we need to pass the actual values here.
})

This is the error:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Evaluation failed: ReferenceError: req is not defined at :2:32

What could be the reason?

1 Answers

The return value from an express route handler doesn't matter, so it can be async

router.post('/search', async (req, res, next) => {
  try {
    const browser = await puppeteer.launch()
    const page = await browser.newPage()
    await page.goto(`https://www.google.com/search?tbm=bks&q=%22this+is%22`)
    const result = await page.evaluate(() => {
      console.log('CLAUSESS:', req.body.clauses)
      const clauses = req.body.clauses
      return clauses.map(clause => clause.textContent)
    })
    result.join('\n')
    await browser.close()
    res.send(result)
  }
  catch (err) {
    next(err)
  }
})
Related