通过 Express res.render 函数传递数组时获取 'undefined'

Getting 'undefined' when passing an array through Express res.render function

我对基本节点应用程序的第一次尝试。

如果我用 console.log(eventsArray) 测试 运行 这个文件(> 节点 index.js),数组成功地从命令中的 scraper 模块打印出数据window,所以我的抓取器模块正在工作。

如果我设置 eventsArray = ['this','is,'a','test','array'];在 index.js 作为测试,然后这些字符串在 运行 将应用程序与 Express 连接后确实会像我想要的那样显示在主页上,因此 Express + Jade 模板正在工作(不需要在此处包含我的 ejs 模板,因为它正在工作)。

问题:如果我尝试 运行 如下所示的应用程序(> 节点 index.js),eventsArray 在传递到 [=36= 时似乎是 'undefined' ] 函数,因此 localhost:3000(主页)

上没有显示任何内容

index.js:

var myScraperModule = require('./src/scraper');  // import my scraper function
var express = require('express');
var app = express();

eventsArray =  myScraperModule.getEvents(); // returns an array

app.set('port', process.env.PORT || 3000);

app.get('/', function(req, res) {
    res.render('index.ejs', {data : eventsArray }); // send array to homepage
});


app.listen(app.get('port'), function(){
    console.log("express started")
});

scraper.js:

// basic web scraper using scraperjs module
var scraperjs = require('scraperjs');

function getEvents(){
scraperjs.StaticScraper.create('https://examplewebsite.com/')
    .scrape(function($) {
        return $("p").map(function() { 
              return $(this).html();
            }
       }).get();
    })
    .then(function(data) { 
        //... clean up the data and return it as eventsClean
        return eventsClean;  // return an array of strings
      } 
    });
}

module.exports = getEvents;

你的 getEvents return 没什么,除了这个 scraperjs.StaticScraper.create 是异步函数,它 return 是一个承诺。

您应该 return 来自 getEvents 的异步结果:

function getEvents(){
    return scraperjs.StaticScraper
      .create('https://examplewebsite.com/')
      .scrape(function($) {
        return $("p").map(function() { 
          return $(this).html();
        }).get();
       })
       .then(function(data) { 
         //... clean up the data and return it as eventsClean
         return eventsClean;  // return an array of strings
       });
}

并在创建承诺链的操作中使用它:

app.get('/', function(req, res) {
  myScraperModule
    .getEvents()
    .then(eventsArray => res.render('index.ejs', {data : eventsArray }));
});