【问题标题】:Sending captured data from an API in node.js to a html table从 node.js 中的 API 将捕获的数据发送到 html 表
【发布时间】:2021-08-18 04:33:41
【问题描述】:

我正在学习 node.js 并致力于一个项目,该项目旨在创建一个 Web 应用程序来为投资者管理股票市场投资组合。我不知道如何将捕获的数据从 API 发送到 html 中的表格单元格。 这是我的 node.js 代码

  node.js file

const express = require("express");
const https = require("https");
const bodyParser = require("body-parser");


const app = express();

app.use(bodyParser.urlencoded({extented:true});

app.get ("/", function(req,res){

//The stock market API
  const url= "https://api.{stock-market-api}"

//https get request to API
  https.get(url, function(response){
    console.log(response.statusCode);

    response.on("data", function(data){
     //converting the API jason data to javascript object
      const stockDataObject = JSON.parse(data);
    //capturing the data I want to a const name companyPrice      
     const companyPrice = stockDataObject.data.comapny1.IN3wmk;
    })
  })


});


app.listen(3000, function(){
  console.log("sever is running");
})
html file

<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>document</title>
    <style media="screen">
    table, th, td {
      border: 1px solid black;
    }
    </style>
  </head>
  <body>
    <h1>Market portfolio</h1>

    <table>
      <thead>
        <tr>
        <th>table head1</th>
        <th>table head2</th>
        <th>table head3</th>
        <th>table head4</th>
        </tr>
      </thead>
      <tbody>
        <tr>
        <td>data1</td>
        <td>data2</td>
        <td>data3</td>
        <td>data4</td>
        </tr>
      </tbody>
    </table>
  </body>
</html>

如何将我从“const comapnyPrice”捕获的数据发送到 html 表中 td 元素中的 data4 单元格。请帮助我,因为我是编码的初学者。非常感谢

【问题讨论】:

  • 你如何提供你的 html 文件?
  • 取而代之的是,您为什么不使用模板文字来呈现整个表格。它是一种选择。

标签: javascript html node.js api web-applications


【解决方案1】:

你说你是一个初学者,这里有很多东西要解开。这更像是一堂课,告诉您如何制作应用程序的主要部分,而不是修复错误的答案。我所能做的就是向您指出一些可能对您有帮助的资源。

EJS Documentation
这用于所谓的服务器端渲染。有了这个,您就可以在将数据提供给客户端之前将其放入文件中。

Fetch Documentation
如果您希望客户端查询数据,请使用此选项。 (意味着数据是通过页面本身的脚本文件加载的)

About Async/Await
fetch 有很多对 Promise 和异步函数的引用,所以这对你有很大的帮助。通过查看您的代码,您似乎也会遇到回调问题(您可能会尝试在某个时候在回调中访问res,这不是一个好主意)。使用 async/await 将帮助您解决这些问题。

PS:很抱歉,如果这不是您所期望的答案,我只是想帮助您。

【讨论】:

  • 我设法通过 ejs 模板将数据传递给 html。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-11
  • 1970-01-01
  • 2018-01-09
  • 2018-03-03
  • 2023-04-05
  • 2019-12-22
  • 1970-01-01
相关资源
最近更新 更多