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

标签 javascript 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 字符串响应。我需要放置不同的内容类型吗?这个函数应该将该值传递给客户端的另一个人吗?

感谢您的帮助!

最佳答案

使用 res.json与 express :

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);
}

关于javascript - 在 Node.js 中响应 JSON 对象(将对象/数组转换为 JSON 字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5892569/

相关文章:

javascript - 对 JSX.Element 与 React.Component 之间的差异以及何时将它们与 React-dom-router 一起使用感到困惑

node.js - Windows 上的 Web3.js 安装错误

javascript - 为什么代码中的 catch 语句没有捕获 async 函数中的错误?

javascript - 清除页面加载时的所有表单

javascript - Webpack 导入 font-awesome 库时出现问题

javascript - jQuery UI 可拖动 : Custom Snap-To Method

javascript - Angular.js 数据访问器

javascript - 用于列出与帐户关联的所有用户池的 AWS javascript API 示例

javascript - 使用 localeCompare 与 === 比较字符串?

javascript - 保持相同的 Puppeteer 页面打开 NodeJS