javascript - 错误 : Evaluation failed: ReferenceError: res is not defined

标签 javascript node.js express puppeteer

我在使用 puppeteer 的 Node 中遇到范围问题。我无法发送在 puppeteer 的评估对象中获得的内容,因为我得到: 错误:评估失败:ReferenceError:res 未定义 我需要帮助。

const express = require('express');
const path = require('path'); // NEW
const puppeteer = require('puppeteer');
const fs = require('fs');

const config = require('../src/config.js');
const app = express();
const port = process.env.PORT || 3006;
const DIST_DIR = path.join(__dirname, '../dist'); // NEW
const HTML_FILE = path.join(DIST_DIR, 'index.html'); // NEW

app.use(express.static(DIST_DIR)); // NEW
app.get('/api', (req, res) => {
  res.send(mockResponse);
});
app.get('/getapi', async (req, res) => {
  req.setTimeout(500000);

  var pal= req.query.palabra;
  function randomIntFromInterval(min, max) { // min and max included
    return Math.floor(Math.random() * (max - min + 1) + min);
  }

  const next_class = 'snByac';

      const browser = await puppeteer.launch({
      headless: false,
    });
      const page = await browser.newPage();

      await page.goto('https://adwords.google.com/ko/KeywordPlanner/Home?', {waitUntil: 'networkidle2'});
      await page.waitFor(randomIntFromInterval(10000,25000));
      await page.type('input[name=identifier]', config.mail);
      await page.click('span.' + next_class);
      await page.waitFor(randomIntFromInterval(20000,23000));
      await page.type('input[name=password]', config.password)
      await page.click('span.' + next_class)
      await page.waitFor(randomIntFromInterval(37000,45000));
      await page.click('[icon="arrow_forward"]')
      await page.waitFor(randomIntFromInterval(3800,6000));
      await page.type('[aria-autocomplete="list"]', pal)
      await page.waitFor(randomIntFromInterval(1400,2400));
      await page.keyboard.press('Enter');
      await page.waitFor(randomIntFromInterval(5000,14000));
      await page.keyboard.press('Enter');
      var hotelJson = {};
      await page.evaluate(() => {
      var hotelsElms = document.querySelectorAll('.keyword._ngcontent-vyt-82');
      hotelsElms.forEach((hotelelement) => {
       hotelJson.name = hotelelement.querySelector('span.keyword._ngcontent-vyt-82').innerText;
        });
      res.json(hotelJson);
});


        await browser.close();

});
app.get('/', (req, res) => {
 res.sendFile(HTML_FILE); // EDIT
});
app.listen(port, function () {
 console.log('App listening on port: ' + port);
});
//app.setTimeout(500000);

我也试过把“res.json (hotelJson);”在“评估”对象之外但返回一个空的 json,就好像“hotelJson”无法在“评估”函数的范围内分配然后恢复为空,我试图用虚假数据填充它并且它也返回空。

最佳答案

Official document - 该方法返回一个 Promise,它解析为 pageFunction 的返回值。

这意味着您可以在 evaluate 函数的“外部”取回一个值。

//...
const result = await page.evaluate(() => {
    var hotelsElms = document.querySelectorAll('.keyword._ngcontent-vyt-82');
    var hotelJson = {};
    hotelsElms.forEach((hotelelement) => {
        hotelJson[name] = hotelelement.querySelector('span.keyword._ngcontent-vyt-82').innerText;
    });
    return hotelJson; // return value to "out site", assign `hotelJson` to `result`
});

// response the data to the client
res.json(result);

// ...

关于javascript - 错误 : Evaluation failed: ReferenceError: res is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57639795/

相关文章:

node.js - 如何从错误对象获取错误状态代码

javascript - 使用 javascript 在页面上搜索

javascript - 可在可滚动容器中排序的 JQuery UI - 排序时滚动位置 "jumps"

javascript - 解析服务器登录返回一个用户,但 req.user 未定义

ios - 在 Node.js 中接收来自 Swift 的 POST 请求

node.js - 在 Chrome 中使用 $window.open() 打开另一个应用程序的新选项卡时隐藏地址栏

Javascript:如何获取数组中特定顺序的值的索引?

javascript - Ajax 使用函数每 x 秒获取 php 数据

node.js - 使用 httpclients axios 和 request-promise 在 node/express js 中读取响应 HEADER 时大写转换为小写

javascript - 从中间件通过 req.body 传递变量