简体   繁体   中英

Node.js - Parsing JSON data into PUG templates

I am trying to parse some JSON data into some elements called homeCards. I use Axios to request the JSON data and have a for loop to iterate through it. I store the fields I want in the title and description variables and pass these variables to the homeCards. My issue is that my title and description variables live inside my axios function, and when I try to assign these values to homeCards, which is declared outside its scope, it can't find them. If I move my homeCard declaration in the Axios function, then I won't be able to call the homeCards in the render function at the bottom of the file. How can I fix this problem? Is there a much easier way to do this?

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;

If I move the relevant code in the router.get calls like so:

    /* 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,
        },
        ]

});

I get the following error: index.pug:19 17| div(class="card-deck") 18| if pageId === 'index' > 19| each item in cards 20| +horizontalCard(item.title,item.imgSrc, item.imgAlt, item.link, item.description) Cannot read property 'length' of undefined. Here is the pug file in question

 //- 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)

If I move the router.get calls inside the .then(response) block like so:

    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);
  });

The homecards display nothing

In your code, the axios({...}).then() block is executed after the main code (assignment to homeCards and calls to router.get ) are completed. This is how Node.js (and JavaScript in general) asynchronous calls work, by design: axios makes network call, so it returns its result as a promise, which gets resolved after the caller function code is executed.

Moving everything, including router.get calls, into an axios .then handler is one option. Another option, if you target Node.js 8+, is to use async/await pattern to write asynchronous code in a synchronous way. This is essentially the same as putting all logic in the axios .then handler, but looks much better.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM