如何将数据从Node.js服务器发送到HTML文档?

我想将从API获取的数据从Node.js上的服务器发送到HTML页面。 下面是我的Node.js代码;

const express = require("express");

const app = express();

const https = require("https");
const bodyparser = require("body-parser");


app.use(express.static("public"));
app.use(bodyparser.urlencoded({
  extended: true
}));



//getting request from browers so sending response
app.get("/", function(req, res) {
  res.sendFile(__dirname + "/index.html");
});


//on getting the post req
app.post("/", function(req, res) {

  const query = req.body.query;
  const appid = "//appid";
  const units = "metric";
  const url = "https://api.openweathermap.org/data/2.5/weather?q=" + query + "&appid=" + appid + "&units=" + units

  https.get(url, function(respond) {

    console.log(respond.statusCode);
    respond.on("data", function(data) {


      const weatherdata = JSON.parse(data)
      console.log(weatherdata);
      const tempe = weatherdata.main.temp;
      const des = weatherdata.weather[0].description;


        res.sendFile(__dirname+"/output");


    });
  });
});




app.listen(8085, function() {

  console.log("server started at port 3000");

});


这是我要向其发送数据的output.html的代码


    <!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Weather Report</title>
    <link rel="stylesheet" href="css/styles.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

        <style>
          .bd-placeholder-img {
            font-size: 1.125rem;
            text-anchor: middle;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
          }

          @media (min-width: 768px) {
            .bd-placeholder-img-lg {
              font-size: 3.5rem;
            }
          }
        </style>



  </head>
  <body class="text-center">
    <section class=" form-signin">
      <div class="headingdiv">
           <form class="form" action="/output" method="get">
              <h1 id="Temperature" name="tem">Tempe here</h1>
                  <p class="mt-5 mb-3 text-muted">&copy; 2020</p>

           </form>
      </div>
    </section>

  </body>
</html>


我使用了Weather API发送数据,我想将该数据显示到新的HTML文档中。

评论
对你的冷漠
对你的冷漠

You need to use ejs or jade template system to fill data into html file and then send it to user in response. For your reference, here's a link

点赞
评论