JSON结构输出

标签 json node.js

我正在完成一项学校作业 Node.js,但无法正确输出。这是 res.end 部分不起作用,但 res.end(stdout); 起作用。为什么?

case "/status":
    /**
     * Run child process "uname -a".
     */
    cp.exec("uname -a", (error, stdout, stderr) => {
        if (error || stderr) {
            // Do something with the error(s)
            console.log("Something went wrong...", error, stderr);
        }

        // status route
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end({
            "uname": stdout
        });
    });
break;

最佳答案

Node.js docs 中所述, res.end 只能采用字符串或缓冲区(或者什么也不做)作为其第一个参数。如果您希望使用它发送 JSON,则必须设置内容类型(您已完成)并对对象进行字符串化:

res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({
    "uname": stdout
}));

这实际上是what Express.js does when you call res.send/res.json on an object .

关于JSON结构输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42554766/

相关文章:

java - Jackson 从子节点反序列化到字段?

Node.js API REST 安全性

node.js - 我在导入 @google-cloud/storage 时遇到错误

javascript - 无法使用 MulterJS 在 Linux 服务器上上传文件

node.js - mongoose 通过嵌套对象 ID 查找返回整个文档

javascript - 哪个先触发,是更早创建的 setTimeout() 还是更早安排的?

Javascript:子对象上的 ForEach

java - — 特殊字符解码

java - 我是 JSON 的新手,有什么方法可以验证 json- 键值对

ios - AFNetworking 与 BaaS?