浏览器不显示 JSON 文件 - Setheader Nodejs

Browser not displaying JSON file - Setheader Nodejs

我正在尝试使用以下代码

在我的浏览器上将内容显示为 JSON 文件
const express = require ("express")
const app = express();

app.get("/test", async(req, res) => {
    const rows = await actiondb();
    res.setHeader("content-type", "application/json")
    res.send(JSON.stringify(rows))
})

即使使用 setheader"content-type", "application/json" 它也不起作用。下图为结果

我期待得到如下内容:

可以做什么?

您的浏览器不会像您在示例中显示的那样原生格式化 JSON 响应。如果您想在浏览器中格式化 JSON 响应,可以将浏览器扩展程序 JSON Formatter 安装到您的浏览器中。这将检测 JSON/JSONP 并为您格式化显示。

安装了扩展程序的示例:

此扩展所做的只是使 JSON 响应更易于阅读,它不会更改返回的内容类型或数据。向 /test 发出请求在有或没有扩展名的情况下都有效。

作为 side-note,您的代码可以简化为使用 express 的 .json() 方法:

const express = require ("express");
const app = express();

app.get("/test", async(req, res) => {
    const rows = await actiondb();
    res.json(rows);
});