2017-09-02 61 views
0

卡住我的第一個非常基本的應用程序。 '繁重'的作品:scrape.scrape();函數導入一個模塊,該模塊返回一個字符串數組(通過刮取外部網站)。如何使用Express將此模塊的數據傳遞給index.ejs?

當我運行'node index.js'時,我看到數組在終端中被返回,當我打開localhost:3000時它只是'hello world'。但是,如果我在本地主機索引頁面上打開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> 

回答

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 index.ejs

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

official ejs documentation here 希望這可以幫助你