JSON结构输出

我正在做一个学校任务,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文档中所指定的那样, res.end只能将一个string或一个缓冲区作为第一个参数,或者根本没有任何作用。 如果你想使用它发送JSON,你将不得不设置内容types(你已经完成)并将对象串联起来:

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

当你在一个对象上调用res.send/res.json时,这就是Express.js所做的 。