NodeJS 映射 API 从 JS 文件中获取的数据到 EJS Table

NodeJS Mapping API data from Fetch in a JS file to an EJS Table

我已从 Coingecko API 检索到 JSON 数据,我希望将其映射到 ejs 文件中的 table,有人知道我该怎么做吗?

获取 EJS 页面,其中包含 API 提取(位于名为 indexRoutes.js 的文件中 来自根文件夹的位置:routes/indexRoutes.js):

router.get("/crypto", ensureAuthenticated,(req, res) => {
  async function getCoins(){
  const api_url =
  "https://api.coingecko.com/api/v3/coins/markets?vs_currency=gbp&order=market_cap_desc&per_page=100&page=1&sparkline=false";
  let fetch_response = await fetch(api_url);
  let json = await fetch_response.json();
  console.log(json);
  }
  getCoins();
  res.render("crypto");
});

我还没有在页面中添加 table 但这里是页面上已有的代码以供参考。文件名 (crypto.ejs) 来自根文件夹 (views/pages/crypto.ejs) 的位置:

<%- include ("./includes/_header.ejs"); %>
<container class="pt-5">
  <div class="row mt-5 d-flex justify-content-center">
    <div class="col-md-5">
      <div class="card card-body">
        <h1 class="d-flex justify-content-center">Cryptocurrency Q&A</h1>
        <!--Accordian for Emissions Q&A-->
        <div class="row d-flex justify-content-center">
          <div
            class="col-md-7 m-1 bg-white parathree text-black text-center p-3 mt-4"
          >
            <div class="accordion accordion-flush" id="accordionFlushExample">
              <div class="accordion-item">
                <h2 class="accordion-header" id="flush-headingOne">
                  <button
                    class="accordion-button collapsed"
                    type="button"
                    data-bs-toggle="collapse"
                    data-bs-target="#flush-collapseOne"
                    aria-expanded="false"
                    aria-controls="flush-collapseOne"
                  >
                    What is a Cryptocurrency?
                  </button>
                </h2>
                <div
                  id="flush-collapseOne"
                  class="accordion-collapse collapse"
                  aria-labelledby="flush-headingOne"
                  data-bs-parent="#accordionFlushExample"
                >
                  <div class="accordion-body">
                    <p>
                      A Cryptocurrency is a digital currency or a decentralized
                      system that has been secured by utilizing cryptography.
                      Cryptocurrency is seen widely as an investment platform
                      that is easily accessible as long as you are over the age
                      of 18. Cryptocurrency started because people were getting
                      fed up with the banks having control of all of their
                      transactions. Groups of cryptographers started to create
                      decentralized methods of payment called Cryptocurrencies,
                      none of the starting ones got enough momentum to become
                      big, until a still unknown identity named "Satoshi
                      Nakamoto" created what is now known as Bitcoin.
                    </p>
                    <p>
                      They wrote a piece of literature called "Bitcoin: A
                      Peer-to-Peer Electronic Cash System", which describes how
                      Bitcoin aims to create a decentralized version of the
                      financial sector which would once again empower the people
                      instead of the banks by using online payments that allow
                      Bitcoin. These decentralized systems are named
                      Blockchains. One downside to Cryptocurrency due to it
                      being electronic, it can be replicated easily until it is
                      worthless, therefore it must have limited supply and be
                      unique for it to be of any value.
                    </p>
                  </div>
                </div>
              </div>
              <div class="accordion-item">
                <h2 class="accordion-header" id="flush-headingTwo">
                  <button
                    class="accordion-button collapsed"
                    type="button"
                    data-bs-toggle="collapse"
                    data-bs-target="#flush-collapseTwo"
                    aria-expanded="false"
                    aria-controls="flush-collapseTwo"
                  >
                    What is a Blockchain and what are its benefits?
                  </button>
                </h2>
                <div
                  id="flush-collapseTwo"
                  class="accordion-collapse collapse"
                  aria-labelledby="flush-headingTwo"
                  data-bs-parent="#accordionFlushExample"
                >
                  <div class="accordion-body">
                    <p>
                      Blockchains are essential for maintaining the "purpose" of
                      Cryptocurrency. They are essentially an electronic ledger
                      that contains all of the transactions made with every
                      Cryptocurrency whilst keeping the owner anonymous. The
                      wallet ID will be kept on each transaction, however, any
                      details that belong to the owner of said wallet will
                      remain unavailable. Therefore, hacking into somebody's
                      account is much harder.
                    </p>

                    <p>
                      For example, if someone tried to hack into your bank
                      account, empty it and change the data, it would be their
                      word against yours and the bank might assume that the
                      withdrawal was made by you as there is only one record to
                      change and the hacker would have changed it due to the
                      system being centralized, whereas with the Blockchain,
                      everybody who owns that Cryptocurrency, has a record of
                      the transactions made, therefore, the hacker would have to
                      change over half of the data, as Cryptocurrency decisions
                      are made final with over 51 percent of the record holders
                      opinions.
                    </p>
                  </div>
                </div>
              </div>
              <div class="accordion-item">
                <h2 class="accordion-header" id="flush-headingThree">
                  <button
                    class="accordion-button collapsed"
                    type="button"
                    data-bs-toggle="collapse"
                    data-bs-target="#flush-collapseThree"
                    aria-expanded="false"
                    aria-controls="flush-collapseThree"
                  >
                  How much of the economy consists of Cryptocurrency?
                  </button>
                </h2>
                <div
                  id="flush-collapseThree"
                  class="accordion-collapse collapse"
                  aria-labelledby="flush-headingThree"
                  data-bs-parent="#accordionFlushExample"
                >
                  <div class="accordion-body">
                    <p>Cryptocurrency is 7 percent of all of the worlds money in total</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="col-md-5">
      <div class="card card-body">
        <h1>Insert Table/List of top Cryptos here. (Using CoinGecko API)</h1>
      </div>
    </div>
  </div>
</container>
<%- include ("./includes/_footer.ejs"); %>

您需要在此处更改一些内容。

首先,您收到来自 API 的响应,但是您没有在嵌套函数“getCoins”之外访问响应。您需要将调用移至异步函数内的 res.render()。

在渲染之前访问数据后,您可以将对象作为第二个参数传递给 ejs 页面以调用 res.render()。

应用这些更改后,您的代码将类似于:

router.get("/crypto", ensureAuthenticated, (req, res) => {
  async function getCoins(){
  const api_url =
  "https://api.coingecko.com/api/v3/coins/markets?vs_currency=gbp&order=market_cap_desc&per_page=100&page=1&sparkline=false";
  let fetch_response = await fetch(api_url);
  let json = await fetch_response.json();
  console.log(json);
  res.render("crypto", { data: json });
  }
  getCoins();
});

现在您已将数据传递到页面,您应该能够在代码标记之间访问它:

<%= data.whateverIsInside %>

这应该允许您在页面上显示它。建议在 EJS 上查看这些资源:

https://ejs.co/#docs

https://github.com/mde/ejs/wiki/Using-EJS-with-Express