Node-Express (module.exports) 变量未定义

雨人

我将直接进入主题。

我有 3 个文件,app.js(这是主要的),cat.js(有一个对象数组)和cats.ejs(路由的渲染文件)。现在我想从我的cats.ejs 文件中遍历我的obj arr。我在 cat.js 中使用了 module.exports = Cats 并在我的 app.js 中使用了它(但我只能在我的 app.js 中使用它,否则会抛出未定义的变量)。

问题是,我应该怎么做才能从我的cats.ejs 文件访问数组?我知道我不擅长解释事情,所以我将包含 3 张图像(每个文件)。

cat.js 文件 [ 在底部我有 module.exports = Cats; ] -> http://prntscr.com/mvwuqs

app.js 文件 -> http://prntscr.com/mvwv7k

cat.ejs 文件 -> http://prntscr.com/mvwvvc

如果这是一个愚蠢的问题,我真的很抱歉,但我无法弄清楚。

阿凡提卡
  1. 您是否在文件末尾导出猫?如果你在做 module.exports,它需要是一个对象。
module.exports = {
  getCats: function() {
    const Cats = [{}, {}, {}];
    return Cats;
  }
};
  1. 导出后,您将能够在 app.js 中访问它。你可以在 res.render 中将它传递给 ejs。
let cats = require('./cat');
app.get('/cats', function(req, res) {
  res.render('cats', { CatsData: cats.getCats() });
});
  1. 在您的 ejs 中,您可以通过以下方式访问它:
<% CatsData.forEach(function(cat, index) { 
    // your data and its properties will be here.
}) %>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章