如何使用Express将此模块的数据传递到index.ejs?

时间:2017-09-02 17:50:16

标签: express npm ejs

坚持我的第一个非常基本的应用程序。 '重吊'有效:scrape.scrape(); function导入一个模块,该模块返回一个字符串数组(通过抓取外部站点)。

当我运行'node index.js'时,我看到在终端中返回的数组,当我打开localhost:3000时,它只是'hello world'。但是如果我在这个localhost索引页面上打开devtools,那么控制台中就没有任何内容。

index.js

var scrape = require('./src/scraper');
var express = require('express');
var app = express();

scrape.scrape();     
// returns ['headline one','headline two', etc...]. Trying to pass this data to index.ejs 


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

app.get('/', function(req, res) {
    res.render('index.ejs');
});

/views/index.ejs

<body>hello world</body>

1 个答案:

答案 0 :(得分:0)

  

你的控制器在这里index.js

var array = scrape.scrape(); //pass this array in res.render 

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

app.get('/', function(req, res) {
    res.render('index.ejs', {data : array});//your data is render through view
});
  

你的ui here index.ejs

<body>hello world</body>
<h1><%= data[0] %></h1> //your data will render here

official ejs documentation here 希望这有助于你

相关问题