【问题标题】:MySQL JSON output to webpageMySQL JSON 输出到网页
【发布时间】:2019-10-27 06:25:26
【问题描述】:

我有一个 Express 节点服务器,它呈现来自 MySQL 数据库的数据。

您将如何将此输出转换为网页?截至目前它只是 JSON,我该如何显示 fx.一个带有数据的 html 页面?

我知道这是个愚蠢的问题。

app.get("/get-cars", function (req, res) {
    let sql = "SELECT * FROM cars";
    let query = db.query(sql, (err, results) => {
        if(err) throw err;
        res.send(results);
    });
});

【问题讨论】:

    标签: mysql json express


    【解决方案1】:

    我认为您的代码应该可以正常工作,它应该将 JSON 数组显示为网页

    res.send(results);
    

    请尝试打开您的网络浏览器并转到 localhost:3000/get-cars ,除非您想以其他格式显示结果,您能澄清一下这里的问题吗?

    【讨论】:

      【解决方案2】:

      如果您想向客户端发送 html 响应而不是 JSON 响应,您可以使用 HTML 模板引擎。

      让我给你看一个Handlebars.js的例子

      第 1 步:运行npm install --save handlebars

      第 2 步:在项目的根目录中创建一个文件 cars.hbs

      第 3 步:在您的 cars.hbs 文件中添加以下代码

      <!DOCTYPE html>
        <html lang="en">
          <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <meta http-equiv="X-UA-Compatible" content="ie=edge">
          <title>Cars</title>
          <style>
            html {
              padding: 0;
              margin: 0;
           }
      
            body {
              position: relative;
              font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
              width: 100%;
              margin: 0;
            }
          </style>
          </head>
      
      
          <body>
            <table>
              <tr>
                  <th>Name</th>
                  <th>Year</th>
                  <th>Engine Size</th>
                  <th>Accelaration</th>
                  <th>Top Speed</th>
                  <th>Consumption</th>
                  <th>Image</th>
              </tr>
              {{#each cars}}
                  <tr>
                      <td>{{this.name}}</td>
                      <td>{{this.enginesize}}</td>
                      <td>{{this.maxpower}}</td>
                      <td>{{this.accelaration}}</td>
                      <td>{{this.topspeed}}</td>
                      <td>{{this.consumption}}</td>
                  </tr>
              {{/each}}
             </table>
           </body>
         </html>
      

      第 4 步:在您的 js 文件(包含 get/cars api)中添加以下代码

      const handlebars = require("handlebars");
      const fs = require("fs");
      app.get("/get-cars", function (req, res) {
         let sql = "SELECT * FROM cars";
         let query = db.query(sql, (err, results) => {
             if(err) throw err;
             const data = { cars: result };
             const template = fs.readFileSync("./cars.hbs", "utf8");
             const html = handlebars.compile(template)(data);
             res.send(html);
         });
      });
      

      第 5 步:打开浏览器并访问 http://localhost:3000/get-cars

      或者,您可以从前端调用 API,并使用您选择的格式在浏览器中显示数据。

      【讨论】:

      • 谢谢!这正是我的想法,但我无法理解它。感谢您为我指明正确的方向。
      • 太棒了。如果这对您有用,请接受并支持答案。
      【解决方案3】:

      您需要的是一个模板引擎。就像我们可以在 php 中生成 html 一样,模板引擎帮助服务器构建页面并以 html 形式返回。

      我想向您介绍 pug 作为 express 的简单模板引擎。

      npm install -S pug
      

      创建一个名为 template.pug 的新文件:

      doctype html
      html(lang="en")
        head
          title="cars data with pug"
        body
          h1 My Cars 
          #container.col
          ul
             each val in dbResult
                li= val.name
      

      在您的快递服务器内部:

      var pug = require("pug");
      
      app.get("/get-cars", function (req, res) {
          const compiledFunction = pug.compileFile("template.pug");
          let sql = "SELECT * FROM cars";
          let query = db.query(sql, (err, results) => {
              if(err) throw err;
               res.send(
                compiledFunction({
                 dbResult: sql
               })
          });
      });
      

      瞧!你应该看到你的html。我会为你留下一些乐趣和一些链接

      1. pug's documentation
      2. https://github.com/pugjs/pug

      【讨论】:

      • 谢谢!这正是我的想法,但我无法理解它。感谢您为我指明正确的方向。
      【解决方案4】:

      好的,所以,根据您的问题,我假设您精通后端方面的事情,但在熟悉前端/渲染框架方面需要一些帮助。

      正如许多开发人员会告诉你的那样,在这种情况下有很多方法可以杀死一只猫,所以我会推荐一些框架和库来帮助你入门:

      建议: - Angular 4+(我个人最喜欢的), - 反应, - Vue 是非常好的前端框架,您可以开始使用它来构建易于扩展和缩小的综合单页应用程序。请注意,还有许多其他前端框架可供您选择。

      知道如何使用 Javascript 是必须的,以便通过呈现从服务器获取的数据(如您的情况)来操作 DOM,所以我将给您两个示例,说明如何使用本机 JS 和 JQuery 来做到这一点图书馆

      1)

      // initiate your request
      xhr = new XMLHttpRequest();
      // check if the server has responded with a status code of 200 after the request has been made
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
          results = JSON.parse(xhr.response);
          // the easiest workaround is to build the html string and then inject it into the tbody
          // the best approach would be to createElements and inject them as you loop through the retuned data
          
          // using the easiest approach
          myString = "";
          for (i = 0; i < results; i++) {
            myString += "<tr><td>" + results[i].jsonElementForHeader1 + "</td><td>" + results[i].jsonElementForHeader2 + "</td></tr>";
          }
          // put the generated stuff from the request into the table body as table rows
          tbody = document.getElementById("tbody").innerHTML = myString
        }
      };
      
      // Add an event listener that checks the progress of the request once initiated
      xhr.addEventListener('progress', evt => {
        if ( evt.lengthComputable ) {
          const perc = evt.loaded / evt.total * 100;
          // log the percentage to the console for monitoring (or render it the way you want)
          console.log(perc);
        }
      }, false);
      
      // specify the method and URL that you would want to query
      xhr.open('POST', 'http://your.domain:port/script', true);
      // important, if you are using cookies,
      xhr.withCredentials = true;
      // initiate the request
      xhr.send(res1);
      <html>
        <head>
          <title>Thingy</title>
        </head>
        <body>
          <table>
            <thead>
              <tr>
                <td>
                  <label>header 1</label>
                </td>
                <td>
                  <label>header 2</label>
                </td>
              </tr>
            </thead>
            <tbody id = 'theTableBody'>
            </tbody>
          </table>
        </body>
      </html>

      2)

      // launch your request to the server
      $.post('http://your.domain:port/APIHandler', {'query': 'parameter(s) JSON Style'}, function(data) {
        // looping through the returned data to handle insertion of the data
        // we will use the recommended way this time round, but generating strings
        tbody = document.getElementById('theTableBody');
        for (i = 0; i < data.length; i++) {
           element = document.createElement("tr");
           element.innerHTML = "<td>" + data[i].desiredElementName1 + "</td><td>" + data[i].desiredElementName2 + "</td>";
           tbody.appendChild(element);
        }
      })
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <html>
        <head>
          <title>Thingy</title>
        </head>
        <body>
          <table>
            <thead>
              <tr>
                <td>
                  <label>header 1</label>
                </td>
                <td>
                  <label>header 2</label>
                </td>
              </tr>
            </thead>
            <tbody id = 'theTableBody'>
            </tbody>
          </table>
        </body>
      </html>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-27
        • 2013-07-31
        • 1970-01-01
        相关资源
        最近更新 更多