将带有Express节点的API数据呈现到html / handlebars

时间:2019-03-07 22:16:05

标签: javascript node.js express templates handlebars.js

我需要帮助将数据从API渲染到html / handlebars。

我对如何在页面上显示数据有些困惑

这就是我到目前为止得到的:

路由文件夹/文件:

const express = require('express');
const router = express.Router();
const us_states = require('../us_state.js');
const fetch = require('node-fetch');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Find My Election', states: us_states });
});

/* GET Election List. */
router.post('/upcomingelections', function(req, res, next) {
        fetch(`https://api.turbovote.org/elections/upcoming?district-divisions=ocd-division/country:us/state:ma,ocd-division/country:us/state:ma/place:wayland
`, {
                method: 'get',
                headers: { 'Accept': 'application/json' },
            })
            .then(res => res.json())
            .then(json => console.log(json));
  res.render('electionlist');
});

module.exports = router;

到目前为止,我已经发出了get请求并存储了数据。然后我使用res.send将数据发送到要渲染的车把页面。 该页面上没有我想要的数据。我不知道我做错了什么。 HTML / HANDLEBARS文件

<div class="resultcontainer">
  <h1 class="resultTitle"> UPCOMING ELECTION(S)</h1> 
   <div id="wrapper">  
      <table id="keywords" cellspacing="0" cellpadding="0">
        <thead>
          <tr>
            <th><span>Description</span></th>
            <th><span>Date</span></th>
            <th><span>Registration Deadline</span></th>
            <th><span>Election Level</span></th>
            <th><span>Website</span></th>
          </tr>
        </thead>
            {{#if json}}
                    <tbody>
                      <tr>
                        <td class="lalign"></td>
                        <td>{{{json.description}}}</td>
                        <td>{{{json.date}}}}</td>
                        <td>{{{json.district-divisions[0]['election-authority-level']}}}</td>
                        <a href={{{json.website}}}>link</a>
                      </tr>
                     </tbody> 
              {{else}}
                <p class="empty">No upcoming election</p>  
            {{/if}}
    </div>
</div>

1 个答案:

答案 0 :(得分:2)

您需要等到fetch完成后才能进行渲染。目前,您无需等待即可进行渲染,也不会将任何数据传递到res.render

此外,您应该始终处理错误。将.catch添加到Promise链中,这样,如果请求失败,则可以结束请求。

router.post('/upcomingelections', function(req, res, next) {
    fetch(`https://api.turbovote.org/elections/upcoming?district-divisions=ocd-division/country:us/state:ma,ocd-division/country:us/state:ma/place:wayland`, {
            method: 'get',
            headers: {
                'Accept': 'application/json'
            },
        })
        .then(res => res.json())
        .then(json => {
            console.log(json);

            res.render('electionlist', { json });
        })
        .catch(err => res.status(500).send(e.message));
});