一尘不染

用Node.js中的JSON对象响应(将对象/数组转换为JSON字符串)

node.js

我是后端代码的新手,我正在尝试创建一个将对我的JSON字符串进行响应的函数。我目前有一个例子

function random(response) {
  console.log("Request handler 'random was called.");
  response.writeHead(200, {"Content-Type": "text/html"});

  response.write("random numbers that should come in the form of json");
  response.end();
}

这基本上只是打印字符串“应该以JSON形式出现的随机数”。我要执行的操作是使用任何数字的JSON字符串进行响应。我需要放置其他内容类型吗?该函数应该将该值传递给客户端的另一个用户吗?

谢谢你的帮助!


阅读 251

收藏
2020-07-07

共1个答案

一尘不染

在Express中使用res.json

function random(response) {
  console.log("response.json sets the appropriate header and performs JSON.stringify");
  response.json({ 
    anObject: { item1: "item1val", item2: "item2val" }, 
    anArray: ["item1", "item2"], 
    another: "item"
  });
}

或者:

function random(response) {
  console.log("Request handler random was called.");
  response.writeHead(200, {"Content-Type": "application/json"});
  var otherArray = ["item1", "item2"];
  var otherObject = { item1: "item1val", item2: "item2val" };
  var json = JSON.stringify({ 
    anObject: otherObject, 
    anArray: otherArray, 
    another: "item"
  });
  response.end(json);
}
2020-07-07