Home > Mobile >  Fetch Data From Api and Replace The Html With Api data Nodejs
Fetch Data From Api and Replace The Html With Api data Nodejs

Time:03-20

I am fetching data from API using Npm package requests in node js

and I am trying to pass API data to HTML but it's not working when I do res.write(mainData) I am getting nothing I should be getting HTML data over there

const fs = require("fs");
const http = require("http");
let requests = require("requests");
/* ------------------------------- */
const mainFile = fs.readFileSync("index.html", "utf-8");
const replaceVal = (oldval, newval) => {
  let temp = oldval.replace("City,Country", newval.main.temp);
  return temp;
};
const server = http.createServer((req, res) => {
  if (req.url == "/") {
requests(
  "https://api.openweathermap.org/data/2.5/weather?q=wah&units=metric&appid=8b949ed0b4efff029e789ed12aab16a0"
)
  .on("data", (cdata) => {
    const objData = JSON.parse(cdata);
    const arrData = [objData];
    const mainData = arrData
      .map((val) => {
        replaceVal(mainFile, val);
      })
      .join("");
    res.write(mainData);
    console.log(mainData);
  })
  .on("end", (err) => {
    if (err) return console.log(err);
    res.end();
  });
  }
});

server.listen(3000, "127.0.0.1", () => {
  console.log("Listining");
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
#main {
  height: 500px;
  width: 300px;
  background-color: #a0b7dc;
  box-shadow: 1px 1px 6px 2px rgb(221, 221, 221);
  border-radius: 10px;
}
#top {
  width: 100%;
  height: 50%;
  display: grid;
  place-items: center ;
}
#bottom {
  width: 100%;
  height: 50%;
  background-color: #c5d0e2;
  border-top-left-radius: 10%;
  border-top-right-radius: 10%;
  display: grid;
  place-items: center;
}
<!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" />
  <link rel="stylesheet" href="style.css" />
  <title>Document</title>
</head>
<body>
  <div id="main">
    <div id="top">
      <h1>icon</h1>
    </div>
    <div id="bottom">
      <h1>City,Country</h1>
      <h1>Tempracture</h1>
    </div>
  </div>
</body>
</html>

CodePudding user response:

There may be other issues, but I can see that you are missing a return:

const mainData = arrData
  .map((val) => {
    replaceVal(mainFile, val);
  })

should be

const mainData = arrData
  .map((val) => {
    return replaceVal(mainFile, val);
  })

or just

const mainData = arrData.map(val => replaceVal(mainFile, val))

See Array.prototype.map.

  • Related