想要通过单击按钮显示来自 API 调用的 JSON 数据,同时使用 EJS、express 和 axios

问题描述 投票:0回答:1

我正在尝试使用 EJS 显示 JSON 数据。 JSON 数据来自一个 URL,我在其中使用 axios 从中获取数据。到目前为止,我有一个用于获取数据和呈现页面的 server.js 文件,以及两个标题为 index.ejs 和 loaded.ejs 的页面。索引文件将只包含一个按钮,单击该按钮可将 JSON 数据显示到 loaded.ejs 页面上。我无法将数据显示在 loaded.ejs 页面上。到目前为止,无论我在加载 loaded.ejs 页面时尝试过什么,它都会显示空白或显示 [object Object]。我对此很陌生,只需要在正确的方向和我出错的地方得到一些指导。

下面的代码是我目前所在的位置。我试图从要显示的 URL 获取数据,但 loaded.ejs 文件的输出返回 [object Object]。

Server.js 文件

// required module to make calls to a REST API
const axios = require('axios');

app.use(bodyParser.urlencoded({ extended: true }));

// set the view engine to ejs
app.set('view engine', 'ejs');

// index page 
app.get('/', function(req, res) {
    res.render("pages/index.ejs", {});
});

app.post('/process_form', function(req, res){
    var url = "https://statsapi.web.nhl.com/api/v1/teams";
    axios.get(url)
        .then((response)=>{
            let teams = response.data;
            res.render('pages/loaded.ejs', {
                team: teams
            });
        });
  
  })




app.listen(8080);
console.log('8080 is the magic port');

Index.ejs 文件

<header>
    
</header>

<main>
<div>
    <form action="/process_form" method="post">
        <h2>Click button below to show Hockey Teams</h2>
        <div class="form-group">
            <input class="btn btn-lg btn-primary btn-block" type="submit">
        </div>
    </form>
</div>
</main>


<footer>

</footer>

Loaded.js文件

<!DOCTYPE html>
<html lang="en">
<head>
    <%- include('../partials/head'); %>

</head>
<body class="container">

    <header>
        
    </header>

    <main>
        <% if (locals.team) { %>
            <p> <%= team %> </p>
        <% } %>

    </main>

    <footer>
        
    </footer>

</body>
</html>
html node.js express axios ejs
1个回答
0
投票

尽管您的问题似乎与 How to display the json data in ejs template?,这里是您如何解决这个问题的方法。

首先,你得到 [object Object] 因为你试图将一个对象呈现为一个字符串,这肯定不是你想要的。

所以,要解决...您首先要研究您正在调用的 API 返回的对象。在浏览器中快速加载 API 会显示对象结构(

teams = response.data
产生一个对象,它内部是一个名为
teams
的对象数组)...因此,请牢记此结构和服务器的当前方式代码写好了,这里是你的
loaded.ejs
可以重新格式化的方法。

<!DOCTYPE html>
<html lang="en">
<head>
    <%- include('../partials/head'); %>

</head>
<body class="container">

    <header>
        
    </header>

    <main>
        <% if (team && team.teams) { %>
        <% for (const t of team.teams) { %>
            <div>
              <p>Team Name <%= t.name %> </p>
              <p>Division <%= t.division.name %> </p>
              <p>Venue <%= t.venue.name %> </p>
            </div>
        <% } %>
        <% } %>

    </main>

    <footer>
        
    </footer>

</body>
</html>

请注意,我删除了

locals
,因为在调用
team
函数后,
res.render()
变量在 ejs 的范围内动态可用。

此外,由于您可以选择多种方式来呈现数据,因此我上面的插图只是您在问题中所要求的微妙指南。

© www.soinside.com 2019 - 2024. All rights reserved.