javascript - 使用nodejs将JSON文件显示到浏览器上

标签 javascript node.js json ajax express

我正在创建一个本地主机服务器并读取文件路径,然后读取 json 文件

我正在 url 中传递文件路径。
像这样的:http://localhost:3000/C:/Users/Desktop/generated.json

服务器端代码

var createError = require("http-errors");
var express = require("express");
var path = require("path");
var PORT = 3000;
var fs = require("fs");
var app = express();
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

const url = require("url");
app.use(function(req, res) {
  let k = req.originalUrl;
  file = k.slice(1);


  fs.exists(file, function(exists) {
    fs.readFile(file, "utf-8", (error, data) => {
      if (error) throw error;
      let jsonData = [];
      jsonData.push(data);
      console.log(jsonData);//just displaying in console
      console.log(data);
      res.render("./main.ejs", { jsonData: jsonData });
    });
  });
});

app.use(function(req, res, next) {
  next(createError(404));
});

app.listen(PORT, function() {
  console.log(`app is listening at port ${PORT}`);
});

这是使用ejs的客户端代码

<!DOCTYPE html>
<html>

<head contentType="application/JSON">


</head>

<body>
    <form>
            <h1>
            <%=JSON.stringify(JSON.parse(jsonData)) %>
        </h1>
            <br />
        <button name="Click to edit" type="submit" style="height:100px ;width:200px ;font-size:20px">
            Click to edit
        </button>
    </form>
</body>

</body>

</html>

显示的输出是这样的: the link to the output how it is shown

所以我无法以正确的方式显示它。
知道我该怎么做吗?

即使我想对 json 文件进行更改并在目标位置反射(reflect)更改

我还没有向编辑按钮添加任何功能。

最佳答案

我猜你的意思是你不希望它“打印得很漂亮”,比如

{
  "key": "value",
  "key2": "value2"
}

而不是一长串......

如果是这样的话,那么你可以这样做:

<code><pre><%=JSON.stringify(JSON.parse(jsonData), null, 2) %></pre></code>

第三个参数为stringify告诉它使用多少个空格作为缩进,并让它漂亮地将 JSON 打印到多行而不是 1 长行。

<code>标签通常具有等宽字体的默认样式,这使得字符排列得更好。

<pre>标签告诉浏览器内容是预先格式化的;应保留空格和换行符。

<小时/>

另请注意,您不应该永远将上述代码公开到公共(public)互联网。这是一个巨大的安全漏洞。您允许任何人从您的硬盘读取任何文件。有很多关于此的文章,但这里有一个讨论此安全风险的示例:

https://blog.rapid7.com/2016/07/29/pentesting-in-the-real-world-local-file-inclusion-with-windows-server-files/

关于javascript - 使用nodejs将JSON文件显示到浏览器上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53077460/

相关文章:

javascript - jquery post 与 Angular 使用 POST 方法

javascript - 从服务器在客户端本地主机发布数据

node.js - 使用模块进行 TypeScript 转换

java - 在 NetBeans 项目中从 org.json 迁移到 Jackson?

javascript - Controller 不是 NaNunction,未定义

javascript - 具体使用 "[]"作为参数如何工作?

node.js - 使用 Node 路由页面时出错错误代码 :Error: ENOENT, stat '/public/index.html'

node.js - bcrypt.compare 与 Promise 总是返回 false

json - Swift 2 & json 发布

c# - ASP WebApi : Prettify ActionResult JSON output