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



卡在我的第一个非常基本的应用程序上。"繁重的举重"作品:scrape.scrape();函数导入一个模块,该模块返回一系列字符串(通过刮去外部站点)。

当我运行'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>

您的控制器在这里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

在这里官方EJS文档希望这对您有帮助

最新更新