我是后端代码的新手,我正在try 创建一个函数来响应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字符串进行响应.我需要换一种内容类型吗?这个函数是否应该将该值传递给另一个函数(比如客户端)?

谢谢你的帮助!

推荐答案

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

Node.js相关问答推荐

在child_Process中持久运行SSH命令

如何在.npmrc中添加 comments ?

下一个API路由如何处理多个并发请求?

npm错误;无法解析依赖项:npm ERR!对等webpack@;5.x.x;来自@webpack-cli/serve@2.0.5";

mongodb首先自连接,然后根据某些条件与另一个表连接

如何创建具有不同对象类型的数组类型

为什么它无法发送发布请求并更改为 chrome 中的获取方法?

Jest - SyntaxError: 不能在@nestjs/axios 的模块外使用 import 语句

Fly.io 启动问题:无法从源获取图像或构建错误:构建错误:连接期间出错:发布...

try 在 NodeJS 项目中实现 SimplePay (OTP) 支付网关,但我无法获得与技术文档中相同的签名

对 google api v3 的 Axios 请求返回加密(?)数据

Mongodb 从文档中获取聚合结果中的特定属性

仅显示用户在 Reactjs 中使用服务器端发布的帖子是 Node Js、Mongodb

NestJS TypeORM 可选查询不起作用

node.js 变量不存在代码块

在 Javascript 逻辑中访问 EJS 变量

file.slim.js 中的苗条是什么

未在 Windows 8.1 上构建的 node 包 - 缺少 Microsoft.Cpp.Default.props

我可以让 node --inspect 自动打开 Chrome

Npm postinstall 仅用于开发