【问题标题】:Serve JSON to client, different project structures [closed]向客户端提供 JSON,不同的项目结构 [关闭]
【发布时间】:2019-08-28 18:13:48
【问题描述】:

您好,我有一个关于如何最有效地将 json 数据提供给客户端的问题,该客户端已在客户端中使用。

我使用的是带有 express 的 NodeJS。

我从我的服务器获取来自外部网站的 json / api 数据,操作数据并希望在客户端使用该数据。

方法一: 我将处理后的 JSON 数据保存在服务器上的 .json 文件中。

我可以根据请求直接从 .json 文件中发送 JSON 数据吗?

方法2:(我认为称为rest api?) 还是我必须将 JSON 数据从 .json 文件放到另一个客户端 (2)。所以我可以通过 get 请求使用来自客户端 (1) 的 Json 数据访问该客户端 (2)?

我以前从未这样做过,想听听您的建议

编辑:

使用junvar的代码,我还是遇到了一些问题:

NodeJS 应用文件:

const http = require('http');
const fs = require('fs');

// const myJson = require(<path to json>);
const myJson = fs.readFileSync("apidata.json");

console.log(myJson);

// const myHtml = require('fs').readFileSync(<path to html>);
const myHtml = fs.readFileSync("new.html");

console.log(myHtml);

http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end(myHtml.replace(/<JSON>/g, JSON.stringify(myJson, '', 2)));

}).listen(8900);

console.log("server is running")

客户端/html文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div>Hi world, here's some JSON: <JSON>.</div>
<div>Check your console too!</div>
<script>
    console.log(<JSON>);
</script>`;

</body>
</html>

在我尝试连接到客户端之前,服务器运行良好。 它表明 myHtml.replace 不是一个函数。

<Buffer 5b 7b 22 6e 61 6d 65 22 3a 22 46 61 6e 74 6f 6d 22 2c 22 73 79 6d 62 6f 6c 22 3a 22 66 74 6d 22 2c 22 63 75 72 72 65 6e 74 5f 70 72 69 63 65 22 3a 30 ... >
<Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 0d 0a 3c 68 74 6d 6c 20 6c 61 6e 67 3d 22 65 6e 22 3e 0d 0a 3c 68 65 61 64 3e 0d 0a 20 20 20 20 3c 6d 65 ... >
server is running
C:\Users\admin\WebstormProjects\expressapp\fuk.js:19
  res.end(myHtml.replace(/<JSON>/g, JSON.stringify(myJson, '', 2)));
                 ^

TypeError: myHtml.replace is not a function

有什么建议吗?

【问题讨论】:

  • 是的,两者都是可能的。方法 2 将是最直接和推荐的方法。方法 1 有助于避免额外的请求。查看任何 express 教程,甚至任何 vanilla node http 服务器教程,因为您的问题和基本概念并不是唯一可以表达的。
  • @junvar 感谢您的回复。我已经在研究方法 2。大多数教程都展示了如何只向客户端发送 json 数据,这使得您无法放入 html 代码。我非常坚持将 json 数据提供给客户端。我将 EJS 用作全局变量并尝试以这种方式为客户端提供 json 服务,但 EJS 存在缺陷。使用
  • 我添加了一个包含最小示例的示例。

标签: javascript html node.js json api


【解决方案1】:

根据我的评论,以下是您可以在本地运行的两种方法的示例。

是的,两者都是可能的。方法 2 将是最直接和推荐的方法。方法 1 有助于避免额外的请求。查看任何 express 教程,甚至任何 vanilla node http 服务器教程,因为您的问题和基本概念并不是唯一可以表达的。

const http = require('http');

// approach 1

// const myJson = require(<path to json>, 'utf-8');
const myJson = {x: 3, y: 5};

// const myHtml = require('fs').readFileSync(<path to html>, 'utf-8');
const myHtml = `
<div>Hi world, here's some JSON: <JSON>.</div>
<div>Check your console too!</div>
<script>
  console.log(<JSON>);
</script>`;

http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html'});
res.end(myHtml.replace(/<JSON>/g, JSON.stringify(myJson, '', 2)));
}).listen(8900);


// approach 2

// const myJson2 = require(<path to json>, 'utf-8');
const myJson2 = {x: 3, y: 5};

// const myHtml2 = require('fs').readFileSync(<path to html>, 'utf-8');
const myHtml2 = `
<div>Hi world, here's some JSON: <span id="json"></span>.</div>
<div>Check your console too!</div>
<script>
    fetch('http://localhost:8901/json')
    .then(response => response.json())
    .then(json => {
        document.getElementById('json').textContent = JSON.stringify(json);
        console.log(json);  
    });
</script>`;

http.createServer((req, res) => {
    if (req.url === '/json') {
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.end(JSON.stringify(myJson2));
} else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(myHtml2);
}
}).listen(8901);

【讨论】:

  • 感谢您努力尝试它,但我仍然有一些问题,请检查我更新的问题以了解我使用的代码。当我尝试连接到该网站时。它显示: myHtml.replace 不是函数。还有其他建议吗?
  • 这是因为fs.readFileSync(path) 返回的是缓冲区而不是字符串。更新了我的评论,应该改为fs.readFileSync(path, 'utf-8')
【解决方案2】:

当您从 express 中收到 (req, res) 参数到您的方法中时。从您的方法发送响应,例如

res.json({
   key1:value1,
   key2:value2
})

【讨论】:

  • 谢谢。并通过 uisng EJS 获取值对吗?我试过了,但我也使用了
  • 从节点服务器制作api,这样你的客户端就可以获取数据了
  • 所以创建/运行不同的客户端,例如 api.coingecko.com/api/v3/coins 。我是否提出了获取请求?
猜你喜欢
  • 2021-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 1970-01-01
  • 2014-06-01
相关资源
最近更新 更多