簡體   English   中英

如何從Node.js服務器發送數據到HTML文件?

[英]How to send data from Node.js server to HTML document?

我想將從 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>


我使用了發送數據的天氣 API,我想將該數據顯示到新的 HTML 文檔中。

需要使用ejs或者jade模板系統將數據填入html文件,然后發送給用戶響應。 供您參考,這里有一個鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM