【问题标题】:Error: Evaluation failed: ReferenceError: req is not defined错误:评估失败:ReferenceError:req 未定义
【发布时间】:2017-11-21 12:15:32
【问题描述】:

我有一个快速设置。由于某种原因,此函数无法识别 req:

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.
})

这是错误:

UnhandledPromiseRejectionWarning:未处理的承诺拒绝 (拒绝 id:1):错误:评估失败:ReferenceError:req is 没有定义的 在:2:32

可能是什么原因?

【问题讨论】:

  • 第 2 行的分号;删除它,看看是否有效
  • @RajkumarSomasundaram 我删除了分号。同样的错误:UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Evaluation failed: ReferenceError: req is not defined at <anonymous>:2:32
  • 可以在第 2 行之前使用 console.log(req) 吗?
  • @RajkumarSomasundaram 有一个大的:IncomingMessage { _readableState: ReadableState { 所以我认为它存在于那里。
  • 我在这里可能是错的,所以要小心:我查看了一些立即调用异步函数表达式的示例,但它们都没有传递参数;我找不到解释,或者这是否是个问题;你可以朝那个方向研究吗?

标签: javascript node.js express


【解决方案1】:

快速路由处理器的返回值无关紧要,可以是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)
  }
})

【讨论】:

  • 奇怪。我仍然收到theerror: Evaluation failed: ReferenceError: req is not defined at <anonymous>:2:32
  • 在这条路由之前有没有中间件在运行?
  • 或者可能编译这段代码来运行它?
  • 我忘记添加bodyParser了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-26
  • 1970-01-01
  • 2022-12-05
  • 2020-04-21
相关资源
最近更新 更多