You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js HTTP服务器的响应中发送JSON对象?

解决Node.js http服务器发送JSON对象的错误问题

你的问题核心在于res.write()方法仅支持字符串或Buffer类型参数,直接传入JavaScript对象必然触发错误。你提到尝试JSON.stringify()未生效,大概率是用法有误,以下是可行的解决方案:

正确实现代码

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'application/json'});
  // 将JavaScript对象转为JSON字符串后传入res.write
  res.write(JSON.stringify({name: 'John Doe', age: 30}));
  res.end();
});

server.listen(3000, () => {
  console.log('Server started on port 3000');
});

简化写法(更推荐)

可以直接用res.end()发送数据,无需分开调用res.write()和res.end():

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'application/json'});
  res.end(JSON.stringify({name: 'John Doe', age: 30}));
});

server.listen(3000, () => {
  console.log('Server started on port 3000');
});

常见错误排查

若你之前使用JSON.stringify()未生效,检查以下几点:

  • 确认拼写正确:是JSON.stringify()而非JSON.Stringify()(注意大小写)
  • 确认将转换后的字符串作为参数传入方法,而非直接传入JSON.stringify函数本身
  • 若对象包含循环引用,JSON.stringify()会报错,需处理循环引用或更换序列化方式

内容的提问来源于stack exchange,提问作者Ahsan Aasim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 16:35:01