javascript - Node.js - 将 JSON 数据解析为 PUG 模板

标签 javascript node.js json pug

我正在尝试将一些 JSON 数据解析为一些名为 homeCards 的元素。我使用 Axios 请求 JSON 数据,并使用 for 循环来迭代它。我将所需的字段存储在标题和描述变量中,并将这些变量传递给 homeCards。我的问题是我的标题和描述变量位于 axios 函数内,当我尝试将这些值分配给在其范围之外声明的 homeCards 时,它找不到它们。如果我在 Axios 函数中移动 homeCard 声明,那么我将无法在文件底部的渲染函数中调用 homeCard。我该如何解决这个问题?有没有更简单的方法来做到这一点?

var express = require('express');
var router = express.Router();
var title = "title"
var description = "description"

const axios = require('axios');

axios({
  url: "https://api-v3.igdb.com/games",
  method: 'GET',
  headers: {
      'Accept': 'application/json',
      'user-key': 'user-key'
  },
  data: "fields name,summary,popularity;sort popularity desc;limit 4;"
})
  .then(response => {
      let r = response.data;
      for (i=0; i<r.length; ++i){
          title = r[i].name;
          description = r[i].summary;
          console.log(title, description);
      }
    })
  .catch(err => {
      console.error(err);
  });


var homeCards = [
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        ]

/* GET home page. */
router.get('/', (req, res, next) => {
  res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
    });

});
/*GET consoles page. */
router.get('/consoles', (req, res, next) => {
    res.render('consoles', { pageId:'consoles',
                             title: 'Consoles', });
});
/*GET about page. */
router.get('/about', (req, res, next) => {
    res.render('about', { pageId:'abuot',
                          title: 'About' });
});

module.exports = router;

如果我像这样移动 router.get 调用中的相关代码:

    /* GET home page. */
router.get('/', (req, res, next) => {
  res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
    });

  const axios = require('axios');

  axios({
    url: "https://api-v3.igdb.com/games",
    method: 'GET',
    headers: {
        'Accept': 'application/json',
        'user-key': 'feaa948461a62d2965098834275aaa2f'
    },
    data: "fields name,summary,popularity;sort popularity desc;limit 4;"
  })
    .then(response => {
        let r = response.data;
        for (i=0; i<r.length; ++i){
            title = r[i].name;
            description = r[i].summary;
            console.log(title, description);
        }
      })
    .catch(err => {
        console.error(err);
    });
    var homeCards = [
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        ]

});

我收到以下错误:index.pug:19 17| div(class="card-deck") 18|如果 pageId === '索引' > 19|卡片中的每个项目 20| +horizo​​ntalCard(item.title,item.imgSrc, item.imgAlt, item.link, item.description) 无法读取未定义的属性“长度”。 这是有问题的 pug 文件

 //- views/index.pug
extends layout

mixin horizontalCard(title, imgSrc, imgAlt, link, description)
    div(class="card bg-secondary mb-3" style="min-width: 230px; max-width: 540px;")
        img(src=imgSrc class="card-img" alt=imgAlt)
        div(class="card-body")
            h5(class="card-title")= title
            p(class="card-text")= description
            p(class="card-text")
                small(class="text-muted")
                a(rel="noreferrer noopener" href=link target="_blank") Visit Website

block content
    h1= title
    P Most Popular Games
    div(class="card-deck")
        if pageId === 'index'
            each item in cards
                +horizontalCard(item.title,item.imgSrc, item.imgAlt, item.link, item.description)

如果我将 router.get 调用移到 .then(response) block 内,如下所示:

    axios({
  url: "https://api-v3.igdb.com/games",
  method: 'GET',
  headers: {
      'Accept': 'application/json',
      'user-key': 'feaa948461a62d2965098834275aaa2f'
  },
  data: "fields name,summary,popularity;sort popularity desc;limit 4;"
})
  .then(response => {
      /* GET home page. */
    router.get('/', (req, res, next) => {
      res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
        });

    });
    var homeCards = [
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        ]
    let r = response.data;
    for (i=0; i<r.length; ++i){
        var title = r[i].name;
        var description = r[i].summary;
        console.log(title, description);
      }
    })
  .catch(err => {
      console.error(err);
  });

主卡不显示任何内容

最佳答案

在您的代码中,axios({...}).then() block 在主代码(对 homeCards 的赋值和对 router.get 的调用)完成之后执行。这就是 Node.js(以及一般的 JavaScript)异步调用的工作原理,按照设计:axios 进行网络调用,因此它以 Promise 的形式返回其结果,该 Promise 在执行调用者函数代码后得到解析。

移动所有东西,包括router.get调用 axios .then处理程序是一种选择。如果您的目标是 Node.js 8+,另一个选择是使用 async/await模式以同步方式编写异步代码。这本质上和把所有逻辑放在 axios .then 中是一样的处理程序,但看起来好多了。

async function init() {
  const response = await axios({...});
  homeCards = ...;
  router.get(...);
  ...
}

init().catch(err => {
  console.error(err);
});

关于javascript - Node.js - 将 JSON 数据解析为 PUG 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56353245/

相关文章:

typescript 中的 Json 属性别名

javascript - Libsodium JS KDF 函数产生不同的输出

node.js - Node : Check Machines OS while in Linux Bash on Windows 10

node.js - 无法连接到我的 Node.js 服务器

node.js - Node Multer 意外字段

ios - objective c 从 url 请求中解析 json

c# - 是否可以将 System.Text.Encoding 类从 JSON 反序列化为 C# 中的代码?

javascript - 单击后退按钮时清除/清空表单数据

javascript - 检查已启用按钮的数组并为每个按钮创建名称 "true"

javascript - 使用 jquery 和 submlit 默认操作将数据发布到远程站点