Home > Mobile >  How to populate the data scrapped from API in node js into EJS template
How to populate the data scrapped from API in node js into EJS template

Time:10-21

My index.js file on root directory

const express = require("express");
const app = express();
const path = require("path");
const axios = require("axios").default;
const cors = require("cors");
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "/views"));

app.use(
  cors({
    origin: "http://localhost:3000",
  })
);

fetchData = async () => {
  const data = await axios.get(
    "https://nepse-data-api.herokuapp.com/data/todaysprice"
  );
  console.log(data);
  return data;
};

app.get("/", (req, res) => {
  const nepseData = fetchData();
  res.render("home.ejs", { nepseData });
});

app.listen(3000, () => {
  console.log("listening to port 3000");
});

My home.ejs file on views directory

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <%= nepseData %>
  </body>
</html>

The browser is displaying this when I run the server

enter image description here

The API is sending this type of data enter image description here

I want to show the name and prices on my ejs file. What should I do now??

CodePudding user response:

You have to add await there:

app.get("/", async (req, res) => {
  const nepseData = await fetchData();
  res.render("home.ejs", { nepseData });
});

And then you can iterate over the data:

<% nepseData.forEach(function(row){ %>

   <%= row.companyName %> <%= row.minPrice %>

<% }); %>
  • Related