如何在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
相关产品推荐
相关产品推荐

