如何在原生Node.js中向客户端返回JSON数据
在Node.js原生HTTP服务器中返回JSON数据
要不用任何框架实现这个需求,你只需要在mainPage函数里完成两个关键步骤:设置正确的响应头,把JavaScript对象序列化为JSON字符串后发送。
修改后的完整代码
const http = require('http'); // 别忘了引入http模块 const server = http.createServer(function(request, response){ switch (request.url){ case '/': mainPage(request, response); break; default: response.writeHead(404); response.end('Page not found'); } }) function mainPage(request, response){ const clientData = {"status": "ok"}; // 1. 设置响应头,告诉客户端返回的是JSON格式 response.writeHead(200, { 'Content-Type': 'application/json' }); // 2. 把JS对象转成JSON字符串,通过response.end发送 response.end(JSON.stringify(clientData)); } // 记得启动服务器,比如监听3000端口 server.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
关键步骤说明
- 设置Content-Type头:必须指定
Content-Type: application/json,否则客户端会把返回的内容当成普通文本处理,无法自动解析为JSON对象。 - 序列化JS对象:
response.end()只能接收字符串或Buffer类型的数据,所以要用JSON.stringify()把你的JavaScript对象转换成JSON格式的字符串。
你也可以把这两步合并成一行(但可读性稍差):
response.writeHead(200, {'Content-Type': 'application/json'}).end(JSON.stringify(clientData));
内容的提问来源于stack exchange,提问作者Eldar Tailov
相关产品推荐
相关产品推荐

