【问题标题】:Return Html page loaded with JSON data in NodeJS返回在 NodeJS 中加载了 JSON 数据的 Html 页面
【发布时间】:2017-11-16 14:40:16
【问题描述】:

我有一个 NodeJs 服务器,它从一个 REST API 获取 JSon 数据。

加载数据后,我想返回一个 HTML 页面并将其加载到那里的表格中。

编辑

我发现我需要 express(更新下面的示例),并使用正确的版本(3.x 到旧版本!)来使用 res.SendFile()。所以现在返回 Html 文件。但是仍然不知道如何加载页面中的数据。

理想情况下,我还希望能够使用 datatables 过滤数据。

NodeJS 服务器路由

var express = require('express');
var app = express();

var path = require('path');
const Request = require('request');
const ServerAddress = ...;

exports.showAll = function(req, res) {
    Request.get(ServerAddress + '/data', function (error, response, body) {
        if (error) {
            throw error;
        }
        const data = JSON.parse(body);
        return res.sendFile(path.resolve(__dirname + '/../index.html'), { result: data });
    });

index.html

<html>
    <head>
        <script src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
        <script src="//cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"></script>
    </head>
    <body>
        <div class="data">
            <table id="resultsTable">
                <thead>
                    <tr>
                        <th>Col1</th>
                        <th>Col2</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>
                        </td>
                        <td>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </body>
</html>

谢谢!

【问题讨论】:

    标签: html json node.js


    【解决方案1】:

    我建议 EJS。它在 Node 中工作得很好,如果你只知道 HTML,它很容易上手。 http://www.embeddedjs.com/getting_started.html https://www.npmjs.com/package/ejs

    【讨论】:

    • 谢谢。我实际上使用了另一个类似的框架handlebarsjs.com,但如果可能的话我不想使用任何框架,所以我可以处理表格过滤等,我似乎无法通过它完成,因为太多隐藏了 JS 功能.. . 虽然我可能错了,我是 js 初学者
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    相关资源
    最近更新 更多