【问题标题】:Is it possible to send multiple data in one view on Node JS?是否可以在 Node JS 的一个视图中发送多个数据?
【发布时间】:2021-12-13 06:59:17
【问题描述】:

我正在尝试将多个数据传递到一个视图。我可以将产品发送给它,但我也想发送类别。我想单独发送它们而不是加入。有人建议我把它放在“then”之后,但我不知道该怎么做。

router.get('/', function (req, res) {
  models.produit.findAll(
    {
      include: 
      [
        {
          model: models.image, as: "images" 
        },
        {
          model: models.promotionproduit, as: "promotionproduits",
          include:[{model: models.promotion, as: "Promotion"}]
        }
      ]})
      .then(data => {
        res.render('home', {
          data: data
        });
      
    }).catch(err => console.log(err));
});

【问题讨论】:

  • 您可以在渲染前多次请求数据。类别是否需要与产品合并,反之亦然?对您正在寻找的显示关系知之甚少
  • 有哪些类别以及如何访问它们?
  • 我想要做的是用数据获取我的产品并进行另一个查询,例如返回带有 data2 的类别,在我看来,我可以执行以下操作:...

标签: javascript node.js express sequelize.js


【解决方案1】:

当然,使用 async/await 来构建您的数据,然后将其传递给视图。

router.get('/', async(req, res) => {

  // define your data var
  const data = {
    errors: {}
    produits: [],
    categories: []
  }

  // get produits
  try {
    data.produits = await models.produit.findAll({
      include: [{
          model: models.image,
          as: "images"
        },
        {
          model: models.promotionproduit,
          as: "promotionproduits",
          include: [{
            model: models.promotion,
            as: "Promotion"
          }]
        }
      ]
    })
  } catch {
    data.errors.produits = 'Échec du chargement des produits.'
  }

  // get categories
  try {
    // as above, do your model...
  } catch {
    data.errors.categories = 'Échec du chargement des catégories.'
  }

  res.render('home', {
    data
  });
});

【讨论】:

  • 我是这门语言的新手,所以谢谢你的回答,你帮了我很多。
  • np,在您看来,只需通过data.categories 访问,这将是一个您可以 forEach 的数组,如果您检查 data.errors.categories,您可以显示错误等。如果您想要它上一级,即。 categories.forEach 就做res.render('home', data);,祝你好运
  • 完美提示
猜你喜欢
  • 1970-01-01
  • 2018-12-10
  • 2020-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-11
  • 2021-02-09
  • 2010-10-05
相关资源
最近更新 更多