我正在完成一项学校作业 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/