错误: 评估失败:ReferenceError: req未定义。

3
我有一个express设置。由于某些原因,此函数未能识别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: 没有处理的 promise 拒绝 (拒绝 ID: 1): 错误: 评估失败: ReferenceError: req 未定义 at :2:32

可能的原因是什么?


在第二行中,去掉分号,看看是否能正常工作。 - Rajkumar Somasundaram
@RajkumarSomasundaram 我删掉了分号。但是还是出现了同样的错误:UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Evaluation failed: ReferenceError: req is not defined at <anonymous>:2:32 - alex
在第二行之前你能 console.log(req) 吗? - Rajkumar Somasundaram
@RajkumarSomasundaram,这里有一个大的:IncomingMessage {_readableState: ReadableState {,所以我认为它存在那里。 - alex
我可能说错了,所以请谨慎:我研究了一些立即调用的异步函数表达式的例子,但是它们都没有传递参数;我找不到解释或者这是否是一个问题;你能否朝着这个方向进行研究? - Rajkumar Somasundaram
1个回答

3
一个express路由处理程序的返回值并不重要,因此它可以是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 - alex
在这个路由之前,你有任何中间件在运行吗? - Matt
或者可能有什么东西可以编译这段代码并运行它? - Matt
我忘记添加bodyParser了。 - alex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接